[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Printing varible with quotes around it

Jack Smith

10/6/2008 3:29:00 PM

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
--
Posted via http://www.ruby-....

3 Answers

Michael Guterl

10/6/2008 3:46:00 PM

0

On Mon, Oct 6, 2008 at 11:29 AM, Jack Smith <js@priceline.com> 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"
>
You need to escape the " with \.

puts "\"This is my text\""

HTH,
Michael Guterl

TPReal

10/6/2008 4:00:00 PM

0

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.
--
Posted via http://www.ruby-....

Brian Candler

10/6/2008 5:07:00 PM

0

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)
--
Posted via http://www.ruby-....