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:
ruby_irb > (1..5).each do |i| ruby_irb > print i ruby_irb > end 12345 => 1..5
ruby_irb > (1..5).each do |i| ruby_irb > puts i ruby_irb > end 1 2 3 4 5 => 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:
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
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"
nil, while p returns some value.
Pretty basic but useful at times. Happy Coding :)