I'm trying to replace a preceding "$" in a string with "\$". For example, "$5 special" should become "\$5 special".
I've tried:
"$5 special".gsub(/^\$/, "\$") => "$5 special"
"$5 special".gsub(/^\$/, "\\$") => "\\$5 special"
"$5 special".gsub(/^\$/, "\\\$") => "\\$5 special"
Anyone know how to do this?
Your second example,
"$5 special".gsub(/^\$/, "\\$")
Should do it. The reason why you see two slashes in your output, is due to Ruby escaping the slash in the string for printing it as a literal. If you print it to standard out, you'd see it's what you expect:
irb(main):009:0> a = "$5 special".gsub(/^\$/, "\\$")
=> "\\$5 special"
irb(main):011:0> print a
\$5 special=> nil
Just use single quotes for the substitution:
>> "$5 special".gsub(/^\$/, '\$') #=> "\\$5 special"
>> puts "$5 special".gsub(/^\$/, '\$') #=> nil
\$5 special
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With