Skip to content

Instantly share code, notes, and snippets.

@MilanGrubnic70
Last active June 13, 2022 19:22
Show Gist options
  • Save MilanGrubnic70/11092705 to your computer and use it in GitHub Desktop.
Save MilanGrubnic70/11092705 to your computer and use it in GitHub Desktop.
puts vs. print vs. p

#puts vs. print vs. p ###The 'puts' (short for "put string") and 'print' commands are both used to display the results of evaluating Ruby code. ###Both 'puts' and 'print' call the 'to_s' method on the object AND return nil.

###The primary difference between them is that 'puts' adds a newline after executing, and 'print' does not. ###They don't RETURN anything so the RETURN value is nil. ###Using 'p' calls the 'inspect' method on the object.

print "Milan"
Milan => nil

puts "Milan"
Milan
=> nil

p "Milan"
"Milan"
=> "Milan"

3.times { print "Hello!" }
Hello!Hello!Hello!=> 3

3.times { puts "Hello!" }
Hello!
Hello!
Hello!
=> 3

3.times { p "Hello!" }
"Hello!"
"Hello!"
"Hello!"
=> 3

@EnterVPL
Copy link

EnterVPL commented Jan 2, 2021

Hi, I added some spaces and enter and made the text preview easier to read.


puts vs. print vs. p

The puts (short for "put string") and print commands are both used to display the results of evaluating Ruby code.

Both puts and print call the to_s method on the object AND return nil.

The primary difference between them is that puts adds a newline after executing, and print does not

They don`t RETURN anything so the RETURN value is nil.

Using p calls the inspect method on the object.

print "Milan"
# Milan => nil

puts "Milan"
# Milan
# => nil


p "Milan"
# "Milan"
# => "Milan"

3.times { print "Hello!" }
# Hello!Hello!Hello!=> 3

3.times { puts "Hello!" }
# Hello!
# Hello!
# Hello!
# => 3

3.times { p "Hello!" }
# "Hello!"
# "Hello!"
# "Hello!"
# => 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment