tags:

views:

206

answers:

4

ruby 1.8.6 (2007-09-24 patchlevel 111)

str = '\&123'
puts "abc".gsub("b", str) => ab123c
puts "abc".gsub("b", "#{str}") => ab123c
puts "abc".gsub("b", str.to_s) => ab123c
puts "abc".gsub("b", '\&123') => ab123c
puts "abc".gsub("b", "\&123") => a&123c <--- This I want to achieve using temporary variable

If I change str = '\&123' to str = "\&123" it works fine, but I get str from match function, so I cannot specify it manually within parantheses.... Is there any way to change string's 'string' to "string" behaviour ?

A: 

Simple:

str = '\&123' <-- the result of your match function
str = str.gsub(/\\/, '\\\\')

You may also want to take a look here.

Paulo Santos
I receive following error : unknown regexp option - g
Stevo
@stevo84 you can leave out the `g` option, as using `gsub` already makes it global.
Jimmy Cuadra
Thanks Jimmy. Rubby isn't my prime language of development. I'm more a .NET guy.
Paulo Santos
A: 

Just remove the backslash:

puts "abc".gsub("b", '&123')

Ampersand is not needed to be protected with backslash inside single quotes (unlike double quotes).

ib
the only problem is, I receive this string from match() function, and it contains a lot of other escaped strings as well (as it is an HTML)...
Stevo
A: 

maybe there is a simpler way, however the code below works

> str = '\&123'
> puts "abc".gsub("b", str.gsub(/\\&/o, '\\\\\&\2\1'))
> => a\&123c
Stevo
A: 

@Valentin

-> I meant that str from match was not taken verbatim. Thus another (simpler) solution appeared, that I was not aware of....

"abc".gsub("b") { str } -> a\&123c

Stevo