CodeNewbie Community 🌱

Aaron McCollum
Aaron McCollum

Posted on • Updated on

The Three Ways to Print in Ruby

In Ruby, there are three main ways to print the result of an operation or expression to the console. This is very similar to console.log() in JavaScript:

  1. puts
  2. print
  3. p

All three of these commands to roughly the same thing, however there are some subtle differences between them.

puts: this prints the result without any type formatting (number vs. string for instance) and each puts statement automatically inserts a new line between them. If you like a nice orderly format for printing outputs, the puts command is it!

print: this is your bare-bones option. The print command will print the raw output to the screen with zero formatting. The user will need to insert their own new lines or other formatting options using escape characters ( \n for a new line, \t for tabulation)

p: this is somewhere in the middle and can be very useful. The p command will print each new output on a new line, but it will also print the output in the style of it's type. If you print 42 as a string, the output will be "42" and if you print 42 as a number, it will print out as 42.

Personally, I will use all three and sometimes will switch them out as needed. I usually use print or p when printing out arrays, since the puts command will print each index of an array on a different line, which takes up a lot of space.

Oldest comments (2)

Collapse
 
djuber profile image
Daniel Uber

There's also pp which is a pretty-printer defined in the standard library. The easiest example showing how it differs from p is probably on larger arrays:

# p just prints the elements as a comma separated list, 
# your console line wraps if it runs out of space
p (0..25).to_a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

# pp puts the elements in a left justified column when 
# the number of items is wider than a certain width, 
# for pp (0..20) I got the horizontal/compact version, but 25
#  is just big enough to cause the vertical display:
pp (0..25).to_a
[0,
 1,
 2,
 3,
 4,
...

 25]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
larrymartin1job profile image
Larry Martin

Great breakdown of printing options in Ruby! I appreciate your practical approach of using puts for clarity, print for simplicity, and p for nuanced outputs. The tip on using print or p for arrays is particularly helpful. Thanks for sharing!
Best Drywall Repair Services in Milliken CO