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:
puts
print
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.
Top comments (3)
There's also
pp
which is a pretty-printer defined in the standard library. The easiest example showing how it differs fromp
is probably on larger arrays:Iβm still dreaming about getting a 3D printer. Not really the main topic, but I read about printing and thought of it. Whoβs actually using 3D printers these days, and what are they printing? Iβm thinking more along the lines of everyday use. Itβs so cool! I could print a bunch of stuff for the kitchen or to organize storage. I even saw someone making jewelry this way. You could even start a decent business.
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