What Is the Difference Between Print Puts and P


Print is as suggested prints out any thing given to it out to the terminal.

ruby_irb >  print 'Hello world'
Hello world => nil


Puts works almost similar to print.

ruby_irb >  puts 'Hello world'
Hello world
=> nil

Difference between print and puts

Above example clarifies that print and puts both can be used to have output on the console. Puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line), whereas print continues printing text onto the same line as the previous time. Consider another example:

Print Example

ruby_irb >  (1..5).each do |i|
ruby_irb >    print i
ruby_irb >  end
12345 => 1..5

Puts Example

ruby_irb >  (1..5).each do |i|
ruby_irb >    puts i
ruby_irb >  end
=> 1..5

Clearly observable difference between two.

The `inspect` method is a built-in method for all classes in Ruby and it gives you a textual representation of the object.


p can be described as puts + inspect. Consider the following

ruby_irb >  class User
ruby_irb >    attr_accessor :name
ruby_irb >  end
 => nil
ruby_irb >  u = User.new
 => #<User:0x000000021ce088>
ruby_irb >  u.name = 'sahil'
 => "sahil"

ruby_irb >  p u
#<User:0x000000021ce088 @name="sahil">
 => #<User:0x000000021ce088 @name="sahil">

Difference between puts and p

Consider the following examples first:

Puts Example

ruby_irb >  def test_puts
ruby_irb >    puts 'I am testing puts'
ruby_irb >  end
 => :test_puts
ruby_irb >  x = test_puts
'I am testing puts'
 => nil
ruby_irb >  x
 => nil

p Example

ruby_irb >  def test_p
ruby_irb >    p 'I am testing p'
ruby_irb >  end
 => :test_p
ruby_irb >  y = test_p
"I am testing p"
 => "I am testing p"
ruby_irb >  y
 => "I am testing p"

Puts return nil, while p returns some value.

Pretty basic but useful at times. Happy Coding :)

Aug 30th, 2014