Download this source
# Strings define some of the basic arithmetic operators, plus as
# you expect, but also multiply.
p 'Stri' + 'ng'
p 'Ho ' * 3
# String brackets with a number gives us access to the byte at that
# position.
d2 = "Foo"
p d2[1]
d2[1] = 99
p d2[1]
puts "Changed str: #{d2}"
# String brackets are much more flexible than that. E.g. they let
# you extract a matching portion:
s = 'Test string'
puts "Matching portion: #{s['est']}"
# and can even be assigned to
s['est'] = 'otal'
puts "String now #{s}"
# Or, wait for it, used with Regexps!
p s[/[A-Z].t/]
# To replace numbered captures!!!
# This operates in place (i.e. modifies the receiver).
s[/([A-Z].)t/,1] = "Toas"
p s
# We can evaluate any code inside a string.
num = 5
message = "The day is long, but the night is auburn-magenta"
c = "Here is a message with #{num * 32} possible meanings: #{message}"
puts c
# frivolous method to handle matching
def regtest(name)
if name =~ /Ros(s|ie).+(B|R)a(mford|ndall)/
puts name + " matched!"
else
puts name + " didn't match!"
end
end
regtest("Ross Bamford") # true
regtest("Rosie Randall") # true
regtest("Boss Bamford") # false
regtest("Ross+++Bandall") # true
regtest("Rob Randall") # false
Running this outputs:
"String"
"Ho Ho Ho "
111
99
Changed str: Fco
Matching portion: est
String now Total string
"Tot"
"Toastal string"
Here is a message with 160 possible meanings: The day is long, but the night is auburn-magenta
Ross Bamford matched!
Rosie Randall matched!
Boss Bamford didn't match!
Ross+++Bandall matched!
Rob Randall didn't match!

