Dumb str.sub question

O

Orion Hunter

I feel really dumb asking this, but I just can't seem to figure it out.

I am trying to parse some text for use in a mysql insert statement. That
being the case, I need to escape out quote characters.

If str= "isn't stands for is not", what I want is a string with "isn\'t
stands for is not"

At first I thought, sure, no problem!! But I can't get it. I've tried the
following:

irb:1> str = "isn't stands for is not"
irb:2> str.sub( '\'', '\'' ) --> "isn't stands for is not" (expected)
irb:3> str.sub( '\'', '\\'' ) --> unterminated string (expected)
irb:4> str.sub( '\'', '\\\' ) --> "isnt stands for is nott stands for is
not" (huh? Why this wierd double take?)
irb:5> str.sub( '\'' ){ |m| m = "\'" } --> "isn't stands for is not"
(expected)
irb:6> str.sub( '\'' ){ |m| m = "\\'" } --> "isn\\'t stands for is not" (why
did it insert TWO \'s?, and not just one? I would have exected the first one
to "escape" the second, thus giving \' as desired)

So, my quesitons are:
1) How do I do my escape character substituion
2) Why did #4 and #6 behave as they did?

Thanks.

_________________________________________________________________
Gift-shop online from the comfort of home at MSN Shopping! No crowds, free
parking. http://shopping.msn.com
 
M

Mike Stok

Mark J. Reed said:
irb(main):006:0> str.sub(/'/) { '\\\'' }
=> "isn\\'t stands for is not"

Sometimes it is useful to pick your quotes carefully e.g.

str.sub(/'/) { '\\\'' }

as you're quoting a single quote then using double quotes saves a \

str.sub(/'/) { "\\'" }

Mike
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top