×

ruby · level 2 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.