Forum: Ruby Printing varible with quotes around it

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
32404bc29ee5801339282d6835b92ea2?d=identicon&s=25 Jack Smith (imperitive)
on 2008-10-06 17:31
I am trying to print my variable in a puts statment but add quotes
around it.

This works but does not put quotes around my text:
z = "This is my text"
puts z

I have tried

puts %Q!z!
and
puts '"#{z}"'

but I can't seem to get my text to print out like:

"This is my text"

thanks

John
D337e2cf7c6d03caac6988d83e0e7f66?d=identicon&s=25 Michael Guterl (Guest)
on 2008-10-06 17:49
(Received via mailing list)
On Mon, Oct 6, 2008 at 11:29 AM, Jack Smith <js@priceline.com> wrote:
> and
> puts '"#{z}"'
>
> but I can't seem to get my text to print out like:
>
> "This is my text"
>
You need to escape the " with \.

puts "\"This is my text\""

HTH,
Michael Guterl
Da33a4ac652c1c8900392a8599206640?d=identicon&s=25 Thomas B. (tpreal)
on 2008-10-06 18:01
Jack Smith wrote:
> I am trying to print my variable in a puts statment but add quotes
> around it.
>
> This works but does not put quotes around my text:
> z = "This is my text"
> puts z
>
> I have tried
>
> puts %Q!z!
> and
> puts '"#{z}"'
>
> but I can't seem to get my text to print out like:
>
> "This is my text"
>
> thanks
>
> John

You get this result if you use p instead of puts. But there's also one
great thing to remember: what p does is in fact:

def p(x) # I skipped the multiple argument variant for simplicity
  puts x.inspect
end

The function inspect is also used when irb presents results of last
operation after the => sign, so you can also do this with arrays, hashes
and all other types of objects, if you want to print them in a nice way,
with all dangerous characters escaped and so on.

TPR.
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (candlerb)
on 2008-10-06 19:08
Jack Smith wrote:
> I have tried
>
> puts %Q!z!
> and
> puts '"#{z}"'

#{...} is only interpolated inside double-quoted strings. So you need:

    puts "\"#{z}\""

(where the double-quotes inside the double-quotes need to be escaped
with a backslash), or

    puts %Q{"#{z}"}

(where they do not)

Or as others have said,

    puts z.inspect

will show your string with double quotes around (but it will also
perform additional transformations, such as turning " to \" and showing
control characters in their escaped form, like \n for newline)
This topic is locked and can not be replied to.