Weird gsub behaviour

ruby 1.8.6 (2007-09-24 patchlevel 111)

str = ‘&123’
puts “abc”.gsub(“b”, str)
puts “abc”.gsub(“b”, “#{str}”)
puts “abc”.gsub(“b”, str.to_s)
puts “abc”.gsub(“b”, ‘&123’)
puts “abc”.gsub(“b”, “&123”)

ruby test.rb
ab123c
ab123c
ab123c
ab123c
a&123c <------------------- This I want to achieve using temporary
variable
Exit code: 0

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???

The exact problem

a = ‘aaa:bbb/
b = ‘<a class=“add_line” href="#" id=“add_fields_invoice_lines”
onclick="add_fields(this, “invoice_lines”, “<fieldset class=
&quot;inputs invoice_line&quot;><ol>\n <li class=
&quot;string required invoice_line_name&quot; id=&quot;”’

str = (b.match /.*/)[0]

puts str

pn=“bbb”

puts a.gsub(“aaa:#{pn}\/”, str)

=> <a class=“add_line” href="#"
id=“add_fields_invoice_lines” onclick="add_fields(this,
“invoice_lines”, "<fieldset class=aaa:bbb/quot;inputs
invoice_lineaaa:bbb/quot;><ol>\n <li class=<aaa:bbb/

quot;string required invoice_line_nameaaa:bbb/quot; id=<aaa:bbb/
quot;"

On Feb 19, 8:47 am, stevo84 [email protected] wrote:

ruby 1.8.6 (2007-09-24 patchlevel 111)

str = ‘&123’
puts “abc”.gsub(“b”, str)
puts “abc”.gsub(“b”, “#{str}”)
puts “abc”.gsub(“b”, str.to_s)
puts “abc”.gsub(“b”, ‘&123’)
puts “abc”.gsub(“b”, “&123”)

Why are you escaping the & at all ?

str = ‘&123’
puts “abc”.gsub(“b”, str)

outputs a&123c for me

Fred

It was received from already escaped html mixed with javascript - that
is why :frowning:
I have no influence on the fact that these slashes are there…

Anyway I have came up with a solution - maybe there is a simpler way,
however the code below works

str = '\&123'

puts "abc".gsub("b", str.gsub(/\&/o, '\\\&\2\1'))

=> a\&123c

Not sure I understand. From

a&123c <------------------- This I want to achieve using temporary

I ask, do you know that & does not need escaping?

“abc”.gsub(“b”, “&123”) # => “a&123c”

Argh - slashes missing → here is the pastie code →
http://pastie.org/832493

On Fri, Feb 19, 2010 at 11:48 AM, stevo84 [email protected] wrote:

Argh - slashes missing → here is the pastie code → http://pastie.org/832493

Easier:

"abc".gsub("b") { |_| str }

There str is taken verbatim.

On Feb 19, 2010, at 5:14 AM, stevo84 wrote:

puts str

pn=“bbb”

puts a.gsub(“aaa:#{pn}\/”, str)

So did you try:
a.gsub(“aaa:#{pn}\/”) { b }

-Rob

ab123c
str = “&123”
.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
.

Rob B. http://agileconsultingllc.com
[email protected]

No, I did not… and it sure works! I knew that it should be easier :slight_smile:

Thank You for another piece of knowledge, Rob and Xavier