Different ways of printing in Ruby
There are three basic output methods in Ruby:
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 "Hello world" Hello world => nil
puts adds a newline to the string it outputs, if there isn’t one already. Alternatively,
>> print "Hello world" Hello world=> nil
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
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?