Usually, programming languages have methods for printing out variables. Ruby is not an exception. We will explore the 3 popular methods for printing variables in the Ruby Programming language.
The print
method
The way print(var)
works is basically converting its value to a string by calling the to_s
method on the object(everything is an object in Ruby) before printing the value and returning nil
to its caller.
The print
method can be easily used for concatenating strings
Having print
as the last operation in a method should be avoided if returning nil is not the desired value
The puts
method
puts
method is not so different from the print
method except for two scenarios:
puts
adds a new line character at the end of the printed value
puts
prints each element in an array on a new line
The p
method
This method can be seen as a debugging tool. It prints more than just the value of a variable, it can print the memory, the object it belongs to. A good name befitting the p
method is the variable inspection method.
Notice that above we have printed the value of STDERR to the console. using the p
method, the module that the constant belongs as well as its name is returned, while puts
only returns the module and memory address of the STDERR constant.
Shalom 🙇