Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between p in a rails view and puts

I am a newbie in Rails. I created a controller and a action. In the corresponding view I used <%= puts "asd" %> once and <%= p "asd" %> the other time.

In case id puts it shows on the console and in case of p it is rendered as HTML. What is the possible reason?

like image 830
Yahoo-Me Avatar asked Nov 30 '10 21:11

Yahoo-Me


People also ask

What is the difference between P and puts in Ruby?

While the print method allows you to print information in the same line even multiple times, the puts method adds a new line at the end of the object. On the other hand, p is useful when you are trying to understand what your code does, e.g. when you are trying to figure out a certain error.

What does P in Ruby mean?

p is a method that shows a more “raw” version of an object. For example: > puts "Ruby Is Cool" Ruby Is Cool > p "Ruby Is Cool" "Ruby Is Cool"

What's the difference between puts and print?

Hi, The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.

Which command is used to add a newline to the end of the output in Ruby?

"\n" is newline, '\n\ is literally backslash and n.


2 Answers

puts calls the method to_s p calls the method inspect

class Foo
  def to_s
    "In #to_s"
  end
  def inspect
    "In #inspect"
  def
def

Semantically, to_s is meant to output the representation of the object to the user, and inspect to hint about the internal properties of the object (kinda like python's repr), but that's just a convention.

If you want to inspect something in your HTML use <%= debug "something" %>

like image 62
Chubas Avatar answered Sep 18 '22 06:09

Chubas


I think you'll find that the p method outputs to the console as well, but the reason why it's "rendered as HTML" is because the p method returns the value passed in, where puts does not.

p is the shorter version of puts something.inspect and is very useful for debugging and that's about it. For outputting strings to the console, it's more preferrable to use puts.

like image 32
Ryan Bigg Avatar answered Sep 18 '22 06:09

Ryan Bigg