ruby · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
text to a fixed width and it lines up in columns.
Text lines up in a when every value takes the same space. .ljust(10) pads a string with spaces on the right until it is 10 characters wide. .rjust(6) pads on the left, which suits numbers. .center(20, "*") pads both sides with stars.
"-" * 20 repeats a string 20 times, which draws a neat line. Inside format, %-12s pads text to 12 on the right, and %8.2f pads a number to 8 on the left.
puts "Receipt".center(20, "*")
puts "Tea".ljust(12) + "2.50".rjust(8)
puts "Cake".ljust(12) + "3.25".rjust(8)
puts "-" * 20
puts format("%-12s%8.2f", "Total", 5.75) If the text is already wider than the width you ask for, Ruby leaves it as it is.
guess first
Mind the gaps. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
puts "Pie".ljust(6, ".") + "3"
puts "Jam".rjust(6, ".")
your turn
Your turn. Print a league table.
Fill in three team names and their points, then press run to see a lined-up table.
fix it
The prices are all over the place. Fix the columns!
- Look at the longest name. Is the width in
.ljustbig enough to hold it? - "Hot chocolate" has 13 characters, so a width of 4 cannot line it up with the others.
- Change ljust(4) to ljust(14), then press run.
nailed it
your text stands in neat columns. :D
.ljustpads on the right,.rjuston the left.- Pick a width bigger than your longest value.
"-" * 20repeats a string to draw a line.
new words in your collection
- pad
- column
This lesson isn’t saved. A free account remembers every lesson you finish.