Exercise 8: Printing, Printing

I will now show you how to create a format string, but rather then using variables, use values by their names. Some of this is a bit more advanced, but don't worry you'll learn what all of these mean later. Just type this in, make it work, and explain each line as best you can with a comment above it.

formatter = "%{first} %{second} %{third} %{fourth}"

puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
puts formatter % {first: true, second: false, third: true, fourth: false}
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter}

puts formatter % {
  first: "I had this thing.",
  second: "That you could type up right.",
  third: "But it didn't sing.",
  fourth: "So I said goodnight."

What You Should See

$ ruby ex8.rb
1 2 3 4
one two three four
true false true false
%{first} %{second} %{third} %{fourth} %{first} %{second} %{third} %{fourth} %{first} %{second} %{third} %{fourth} %{first} %{second} %{third} %{fourth}
I had this thing. That you could type up right. But it didn't sing. So I said goodnight.

Study this carefully and try to see how I put the formatter inside the formatter.

Study Drills

  1. Do your checks of your work, write down your mistakes, and try not to make them on the next exercise.
  2. Notice that the last line of output uses both single-quotes and double-quotes for individual pieces. Why do you think that is?

Common Student Questions

Should I use %{} or #{} for formatting?
You will almost always use #{} to format your strings, but there are times when you want to apply the same format to multiple values. That's when %{} comes in handy.
Why do I have to put quotes around "one" but not around true or false?
That's because Ruby recognizes true and false as keywords representing the concept of true and false. If you put quotes around them then they are turned into strings and won't work right. You'll learn more about how these work in Exercise 27.