Ruby, lesson 8
Most real input is messy text: extra spaces, odd capitals, several values crammed onto one
line. Ruby's String class has a method for nearly every clean-up job. This lesson tours the
useful ones and then puts the whole course together in one program.
These methods return a new string and leave the original alone. Most have a ! twin, such
as strip!, that changes the string in place.
Indexing works like arrays: positions start at 0 and negative numbers count from the end.
split breaks a string into an array; join glues an array back into a string.
With no argument, split breaks on any run of whitespace and ignores spaces at the ends,
which is exactly what you want for user input.
2 exercises to try what you just read.
sub replaces the first match and gsub replaces all of them:
ljust, rjust and center pad a string to a given width. The optional second argument is
the padding character.
Together with format("%.2f", amount) from lesson 3, these let you print neat tables.
Read a person's full name on one line. It may have extra spaces and messy capitals. Print their initials and a username:
For the input ada LOVELACE the output is:
Time to combine everything: input, arithmetic, loops, a method, an array and string formatting.
Each line of input describes one item bought: a name, a quantity and a unit price, separated
by spaces, for example apple 3 0.50. Read lines until the input ends. Print a receipt:
TOTAL padded on the right with spaces to 12 characters, followed by the grand total
formatted the same way as the line totals.Items: N, where N is the sum of all the quantities.For this input:
the output is:
If there are no items, print only the dashes, TOTAL with 0.00, and Items: 0.
raw = " Hello Ruby \n"
raw.chomp # " Hello Ruby " (drops the trailing newline)
raw.strip # "Hello Ruby" (drops whitespace at both ends)
"ruby".upcase # "RUBY"
"RUBY".downcase # "ruby"
"ruby".capitalize # "Ruby"
"stressed".reverse # "desserts"title = "The Ruby Way"
title.length # 12
title.include?("Ruby") # true
title.start_with?("The") # true
title.count("aeiou") # 3 (counts every vowel character)
title[0] # "T"
title[4, 4] # "Ruby" (start at 4, take 4 characters)
title[-3..] # "Way" (from the third-last character to the end)
title.chars.first(3) # ["T", "h", "e"]"red,green,blue".split(",") # ["red", "green", "blue"]
" lots of space ".split # ["lots", "of", "space"]
%w[a b c].join("-") # "a-b-c""a-b-c".sub("-", "+") # "a+b-c"
"a-b-c".gsub("-", "+") # "a+b+c""Tea".ljust(8, ".") # "Tea....."
"4.50".rjust(7) # " 4.50"
"MENU".center(10, "*") # "***MENU***"
"-" * 10 # "----------"Initials: A.L.
Username: alovelaceapple 3 0.50
bread 1 2.25
cheese 2 4.10Apple....... 1.50
Bread....... 2.25
Cheese...... 8.20
--------------------
TOTAL 11.95
Items: 6