[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

gsub method question

Hoppy

5/10/2006 5:19:00 PM

str = "$$$$$$$$"
str.gsub(/([$(&])/, '/\1') # => "/$/$/$/$/$/$/$/$"

Now how do I return this instead: "\$\$\$\$\$\$\$\$"?
# each matched character preceded by a single backslash

I've looked up http://rubygarden.org/ruby?Rege... for clues but
that "multitude of backslashes" isn't clear to me at this point.

(Using ruby 1.8.4 (2005-12-24) [i386-cygwin])

5 Answers

uncutstone

5/10/2006 5:38:00 PM

0

please try this:

str = "$$$$$$$$"
str.gsub(/([$(&])/, '\\\\\1')

result :
\$\$\$\$\$\$\$\$

Jeff Schwab

5/10/2006 5:42:00 PM

0

Hoppy wrote:
> str = "$$$$$$$$"
> str.gsub(/([$(&])/, '/\1') # => "/$/$/$/$/$/$/$/$"
>
> Now how do I return this instead: "\$\$\$\$\$\$\$\$"?
> # each matched character preceded by a single backslash

irb(main):032:0> puts str.gsub(/([$(&])/, '\\\\\1')
\$\$\$\$\$\$\$\$
=> nil

A bitch, no?

Hoppy

5/10/2006 5:51:00 PM

0

Works just fine. Thanks.

I was testing all this using irb and getting double backslashes must be
normal in that context (???):

$ irb
irb(main):001:0> str = "$$$$$$$$"
=> "$$$$$$$$"
irb(main):002:0> str.gsub(/([$(&])/, '\\\\\1')
=> "\\$\\$\\$\\$\\$\\$\\$\\$"
irb(main):003:0>

uncutstone

5/10/2006 6:08:00 PM

0

double backslashes means one .
The first backslash is escape character.

Hoppy

5/10/2006 6:18:00 PM

0

Nice to know.