Developers learning ruby for the first time tend to learn puts
before or around the same time as p
. Both methods print to the terminal (or the server, if you're using rails or sinatra). puts
seems like a nice counterpoint to gets
, as in gets.chomp
: gets
gets information from the user, and puts
puts it back on their screen. I'm inclined to disagree with this inclination strongly and say to never use puts
(it's objectively worse), but there are cases where it's useful.
If you're writing a program that runs in the terminal, puts
can be useful. It's a more aesthetic way to print information and directions to the user. I could argue that anyone using the terminal to run your program is likely a developer and won't have any problem with seeing quotation marks, but I won't because I know I've been known to not give UI as much credence as it deserves.
In essentially any other case when you want something printed, use p
. This is a great tool for debugging. If you're not getting the output or behavior that you expect, print out all of your variables. If your web request to your API isn't sending back good data, p
a bunch of stuff in your API's controller.
Something I see people new to ruby doing a lot is printing things inside of methods.
def sum(a, b)
p a + b
end
sum(3, 5) # => 8
Within a method, it is almost always better to return rather than print. You can still print the output when you're calling the method:
def sum(a, b)
return a + b
end
p sum(3, 5) # => 8
This makes the method more reusable. The exception to this would be if printing is part of the intended functionality of the method; in that case, the method should be named accordingly:
def print_sum(a, b)
p a + b
end
sum(3, 5) # => 8
It's worth noting, though, that even in this case, the method returns a value, since ruby has implicit return. You can assign a variable to the returned value.
def print_sum(a, b)
p a + b
end
x = sum(3, 5) # => 8
p x + 2 # => 10
Using puts
inside of the method will not return anything, though (or, if there's something before the puts
, that'll be returned instead):
def print_sum(a, b)
puts a + b
end
x = sum(3, 5) # => 8
p x # => nil