gsub method question

H

Hoppy

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?RegexpCookbook 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])
 
U

uncutstone

please try this:

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

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

Hoppy

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>
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top