Skip to content

Instantly share code, notes, and snippets.

@joshsarna
Last active July 11, 2019 22:38
Show Gist options
  • Save joshsarna/c6bd5a75ec179b770d73d579818c5cfb to your computer and use it in GitHub Desktop.
Save joshsarna/c6bd5a75ec179b770d73d579818c5cfb to your computer and use it in GitHub Desktop.

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.

Times to use puts

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.

Times to use p

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.

Times to use return

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment