Printing varible with quotes around it

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

Jack S. 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.

On Mon, Oct 6, 2008 at 11:29 AM, Jack S. [email protected] 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 G.

Jack S. 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)

Try var.to_json, or var.inspect.