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?
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.
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"
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.
"\n" is newline, '\n\ is literally backslash and n.
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" %>
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With