On Aug 16, 10:28 am, Alvaro P. [email protected] wrote:
that´s very interesting, I had already notice that p and puts work
differently, i’ll search about that #inspect thing…
Let me try to explain this:
@a = “foo”
@a is now a 3-character string (not 5 characters; the double quotes
aren’t part of the string).
puts @a, @a.inspect
As Austin said, the ‘p’ method calls the #inspect method on its
arguments. Inspect tries to show you what type an object is, so (in
the above) it puts double-quotes around the 3 characters in @a to show
you that it’s a string.
irb also uses #inspect to show you the value of the last expression on
irb(main):001:0> @a = “foo”
See? Those double quotes aren’t part of the actual string, they’re
just there to show you what’s inside the string.
Now, let’s create a string that has a double quote character inside
@b = ‘foo"bar’
puts @b, @b.length, @b.inspect
The string is exactly 7 characters long. When you call #inspect, it
puts double quotes around the string when showing it to you. And, so
that you know that the double quote in the middle isn’t the end of the
string, it shows you a source-code-like representation, a backslash
before the double quote.
This same confusion is seen in this thread already. When you wrote:
…there’s no possible way to write in Ruby a string like this:
what did you mean? A 7 character string with double quotes at either
end? Or a 9 character string with two double quotes at each end?
As Austin showed, there are plenty of ways to create either. You just
need to not confuse the contents of the string what irb and #inspect
are showing you in their attempt to be clear about the contents of the