puts, print and p

puts adds newline

The puts method writes each argument on its own line by adding a newline automatically.

The classic printing primer shows the same call, and here is how it behaves with an array.

puts "one" puts "two" puts [1, 2]

ruby puts_demo.rb

one
two
1
2

print does not

The print method writes exactly what it receives, with no newline added.

Join fragments with print and add the newline yourself when the line is complete.

print "one, " print "two" print "\n"

ruby print_demo.rb

one, two

p shows inspect

The p method writes the inspect form, which reveals the type behind the value.

Quotes around one mean a string and brackets mean an array, so the structure stays visible.

p "one" p [1, "two"] p({ name: "Ada" })

ruby p_demo.rb

"one"
[1, "two"]
{name: "Ada"}

printf basics

The printf method formats values into a template with placeholders for strings and numbers.

Minus ten in %-10s pads the name to ten columns, and zero four in %04d pads the number with zeros.

printf("%-10s %04d\n", "Ada", 42)

ruby printf_demo.rb

Ada 0042

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does puts do with an array argument?

    Answer

    Prints each element on its own line, flattening nested arrays

    puts calls to_s on each element and adds a newline, which is why an array arrives line by line.

  2. What does this program print? puts "one" puts "two" puts [1, 2]

    Answer

    one / two / 1 / 2

    Each puts call ends its line, and the array is printed element by element.

  3. What does this program print? print "one, " print "two" print "\n"

    Answer

    one, two

    print adds no newline, so the fragments join, and the explicit \n ends the line.

  4. What does this program print? p "one"

    Answer

    "one"

    p writes the inspect form, and a string keeps its quotes there.

  5. What does this program print? p({ name: "Ada" })

    Answer

    {name: "Ada"}

    Ruby 3.4 prints a symbol key in the short form inside inspect.

  6. What does this program print? printf("%-10s %04d\n", "Ada", 42)

    Answer

    Ada 0042

    %-10s pads the name to ten columns on the right, and %04d pads the number with zeros.

  7. Which method does p use to show a value?

    Answer

    inspect

    That is why quotes, brackets and the structure stay visible.

  8. How much does print add to what it is given?

    Answer

    Nothing

    The newline is yours to add when the line is complete.

  9. What does this program print? puts [1, [2, 3]]

    Answer

    1 / 2 / 3

    puts recurses into nested arrays and prints every element on its own line.

  10. In a printf template, what does %04d ask for?

    Answer

    An integer padded with zeros to four digits

    d is an integer, 4 is the width, and the leading zero asks for zero padding.

Article author: Arthur Isaev