Skip to content

Instantly share code, notes, and snippets.

@caioertai
Last active July 8, 2020 02:00
Show Gist options
  • Save caioertai/8b9747cad9a9492b285ae981ae7e568e to your computer and use it in GitHub Desktop.
Save caioertai/8b9747cad9a9492b285ae981ae7e568e to your computer and use it in GitHub Desktop.

Differences between p and puts in Ruby

In short

p

Prints an inspected version of the argument AND returns the argument.

[1] pry(main)> name = p [["Hello"]]
[["Hello"]]
=> [["Hello"]]
[2] pry(main)> name
=> [["Hello"]]

puts

Never use for debugging. Prints an string version of the argument AND returns nil.

[1] pry(main)> name = puts [["Hello"]]
Hello
=> nil
[2] pry(main)> name
=> nil

Longer version

puts

It prints...

... a string version of the object (it essentially calls to_s on it) in a line.

For example:

puts [["Hello"]]

Will print Hello. With no indication of the class of the objects being printed.

It returns...

... always: nil.

So:

def full_name(first_name, last_name)
  puts "#{first_name} #{last_name}"
end

my_name = full_name("Caio", "Andrade")
my_name # => nil

puts will ALWAYS return nil. For this reason. NEVER use puts for debugging.


p

It prints...

... an inspected form of the object in a line.

For example:

p [["Hello"]]

Will print [["Hello"]] with its visible string and array delimiters.

It returns...

... the printed object.

So:

p [1, 2, 3, 4]

Will return the same array [1, 2, 3, 4]

And:

def full_name(first_name, last_name)
  p "#{first_name} #{last_name}"
end

my_name = full_name("Caio", "Andrade")
my_name # => "Caio Andrade"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment