Reputation: 855
I tried both approaches and both print to the console.
puts "Hello World"
print_info "Hello World"
What is the real difference between them and which approach is better than another?
Upvotes: 0
Views: 1801
Reputation: 1902
To start print_info is not standard ruby. Could be a rails thing? I dunno.
Now two actual choices puts vs p
puts outputs data using to_s to convert to strings. It has a special case for arrays, putting each array element on its own line. It returns nil
p outputs data using inspect to convert to strings. It has no special case for arrays. It returns its arguments singly if there is only one or in an array if there is more than one.
Which is better? It depends if you want to_s or inspect. I find that p is useful in debugging situations as it can "peek" at values without needing special debug code.
For example the code:
result = my_object.my_method(arg1, arg2)
can be instrumented as:
result = p my_object.my_method(p(arg1), p(arg2))
All things said though puts is more popular, so that is what I normally use.
Also don't forget pp which is pretty print, that prints out data in a more meaningful way. Before Ruby 2.6 you'll need to remember to:
require 'pp'
Upvotes: 3