You may have notices that I swapped the case of my string, as an example, in the Here document demonstration. That's just the tip of the iceberg - there are a large number of methods that you can run on Ruby strings.
METHODS THAT ARE OPERATORS
Operators such as + and * work on strings (concatenate and replicate). The % operator is a short form for sprintf, and the << operator is the same as +. You can treat a character string as an array of characters too.
Example:
Currencyformat = "%.2f"
desert = ["Sticky toffee pudding",
"Rhubarb crumble",
"Bread and butter pudding",
"Jam rolly polly",
"Spotted Dick"]
withon = ["ice cream","cream",
"custard"]
take = desert[rand(desert.length).to_i]
topped = withon[rand(withon.length).to_i]
sweet = take + " and " + topped + "\n"
print "Your desert is #{sweet}"
print "\nA party of 4? ...\n"
print sweet * 4
bill = 7.5
print "Your bill is " + Currencyformat % bill + " today\n"
Note the use of the rand function, used in conjunction with length to choose a random member from an array (and an interesting sweet!). Also note the neat way that we can store a format string in a constant so that we can use it consistently and immutably throughout.
earth-wind-and-fire:~/ruby/r109 grahamellis$ ruby sop.rb
Your desert is Bread and butter pudding and ice cream
A party of 4? ...
Bread and butter pudding and ice cream
Bread and butter pudding and ice cream
Bread and butter pudding and ice cream
Bread and butter pudding and ice cream
Your bill is 7.50 today
earth-wind-and-fire:~/ruby/r109 grahamellis$
OTHER METHODS
To change case:
capitalize - first character to upper, rest to lower
downcase - all to lower case
swapcase - changes the case of all letters
upcase - all to upper case
To rejustify:
center - add white space padding to center string
ljust - pads string, left justified
rjust - pads string, right justified
To trim:
chop - remove last character
chomp - remove trailing line separators
squeeze - reduces successive equal characters to singles
strip - deletes leading and trailing white space
To examine:
count - return a count of matches
empty? - returns true if empty
include? - is a specified target string present in the source?
index - return the position of one string in another
length or size - return the length of a string
rindex - returns the last position of one string in another
slice - returns a partial string
To encode and alter:
crypt - password encryption
delete - delete an intersection
dump - adds extra \ characters to escape specials
hex - takes string as hex digits and returns number
next or succ - successive or next string (eg ba -> bb)
oct - take string as octal digits and returns number
replace - replace one string with another
reverse - turns the string around
slice! - DELETES a partial string and returns the part deleted
split - returns an array of partial strings exploded at separator
sum - returns a checksum of the string
to_f and to_i - return string converted to float and integer
tr - to map all occurrences of specified char(s) to other char(s)
tr_s - as tr, then squeeze out resultant duplicates
unpack - to extract from a string into an array using a template
To iterate:
each - process each character in turn
each_line - process each line in a string
each_byte - process each byte in turn
upto - iterate through successive strings (see "next" above)
Let's see the sort of thing we can do with those - reading some data on A roads that's saved on the end of a program into a single string object, then stepping through each of the lines one at a time and extracting information from them. In practise, just the sort of thing that you might want to do!
info = DATA.read
footers = {}
info.each_line do |aroad|
aroad.strip
cf = aroad.index('(')
comment = nil
if cf != nil
comment = aroad.slice!(cf,aroad.length)
end
number, afrom, ajunk, ato = aroad.split
print "The #{number} runs from #{afrom.upcase.center(15)} " +
"to #{ato}\n"
footers[number] = comment.tr("()","[]") if comment
end
p footers
__END__
A1 London to Edinburgh (The Great North Road)
A2 London to Dover (Watling Street)
A3 London to Portsmouth (Portsmouth Road)
A4 London to Bristol (The Great West Road, or Bath Road)
A5 London to Holyhead (Watling Street)
A6 Luton to Carlisle (The A6 splits off from the A5 at St.
Albans - though the A6 as numbered today starts at Luton)
A7 Edinburgh to Carlisle
A8 Edinburgh to Greenock
A9 Edinburgh to Thurso
And here's the sort of output that produces:
earth-wind-and-fire:~/ruby/r109 grahamellis$ ruby stdo.rb
The A1 runs from LONDON to Edinburgh
The A2 runs from LONDON to Dover
The A3 runs from LONDON to Portsmouth
The A4 runs from LONDON to Bristol
The A5 runs from LONDON to Holyhead
The A6 runs from LUTON to Carlisle
The A7 runs from EDINBURGH to Carlisle
The A8 runs from EDINBURGH to Greenock
The A9 runs from EDINBURGH to Thurso
{"A1"=>"[The Great North Road]\n",
"A2"=>"[Watling Street]\n",
"A3"=>"[Portsmouth Road]\n",
"A4"=>"[The Great West Road, or Bath Road]\n",
"A5"=>"[Watling Street]\n",
"A6"=>"[The A6 splits off from the A5 at St. Albans -
though the A6 as numbered today starts at Luton]\n"}
earth-wind-and-fire:~/ruby/r109 grahamellis$
See also
Training Courses in Ruby