Learn/Ruby/8. Strings and a small project
Lesson 8 of 8
Sign in

Ruby, lesson 8

Strings and a small project

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.

Cleaning up

These methods return a new string and leave the original alone. Most have a ! twin, such as strip!, that changes the string in place.

Looking inside a string

Indexing works like arrays: positions start at 0 and negative numbers count from the end.

Splitting and joining

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.

Replacing

2 exercises to try what you just read.

Exercise 1

Username maker

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

sub replaces the first match and gsub replaces all of them:

Lining things up

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.

Further reading

  • Ruby docs: String
  • Ruby docs: Format specifications

Read a person's full name on one line. It may have extra spaces and messy capitals. Print their initials and a username:

  • Initials: the first letter of every name part, uppercase, each followed by a dot.
  • Username: the first letter of the first part followed by the whole last part, all lowercase. If there is only one part, the username is that part in lowercase.

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:

  1. For each item, one line: the item name capitalized and padded on the right with dots to 12 characters, followed by the line total (quantity times price) with two decimals, padded on the left with spaces to 8 characters.
  2. A line of 20 dashes.
  3. TOTAL padded on the right with spaces to 12 characters, followed by the grand total formatted the same way as the line totals.
  4. 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: alovelace
apple 3 0.50
bread 1 2.25
cheese 2 4.10
Apple.......    1.50
Bread.......    2.25
Cheese......    8.20
--------------------
TOTAL          11.95
Items: 6