Printing varible with quotes around it

J

Jack Smith

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
 
M

Michael Guterl

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"
You need to escape the " with \.

puts "\"This is my text\""

HTH,
Michael Guterl
 
T

Thomas B.

Jack said:
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.
 
B

Brian Candler

Jack said:
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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top