Ruby

Different ways of printing in Ruby

There are three basic output methods in Ruby: print, puts and p. All these methods are used to output messages, results and valuable information during the execution of a Ruby program. However, there are some differences which are going to be demonstrated in this minipost.

We start with the most common way to output in a Ruby program, the method puts.

>> puts "Hello world"
Hello world
=> nil

The method puts adds a newline to the string it outputs, if there isn’t one already. Alternatively, print does print exactly what is instructed to print without the addition of an extra line at the end of the outputted string. Thus printing the actual string by leaving the cursor in the same line.

>> print "Hello world"
Hello world=> nil

Lastly, p outputs an inspected string, which may contain additional information about the kind of object that it is printing. In the following example, we have instructed to output the same string as before and we can notice that the output is in string notation with the addition of a new line at the end of it.

>> p "Hello world"
"Hello world"
=> "Hello world"

We can also notice for the irb session output that the return of the method p is not nil like with puts and print, but the actual string in string notation.

One very common use of p is when we want to output couple of variables in an array notation:

>> a = 1
=> 1
>> b = 2
=> 2
c = 3
=> 3

>> p a, b, c
1
2
3
=> [1, 2, 3]

Thus the return of p method called with multiple variables is an array containing all the values of the printed variables. Interesting eh?

Buy Me A Coffee

Read also the following