tags:

views:

54

answers:

2
irb(main):051:0> "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/,"#{$1} ?")  
=> "ts_id > ?"
irb(main):052:0> "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/,"#{$1} ?")
=> "ts_id < ?"

Can anyone enlighten me?

+2  A: 
irb(main):001:0>  "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/,"#{$1} ?")
=> "ts_id  ?"
irb(main):002:0>  "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/,"#{$1} ?")
=> "ts_id < ?"

Note, that I used fresh started irb, where the $1 was nil. That's all because when using .gsub(...,..$1..), when calculatings the "part right from ," the $1 is not generated by "left part from ," yet.

So do this:

irb(main):001:0> "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/,'\1 ?')
=> "ts_id < ?"

Or this:

irb(main):001:0> "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/){"#{$1} ?"}
=> "ts_id < ?"
Nakilon
+5  A: 

The problem is that the variable $1 is interpolated into the argument string before gsub is run, meaning that the previous value of $1 is what the symbol gets replaced with. You can replace the second argument with '\1 ?' to get the intended effect.

Chuck
I wish I know English so good to tell the main idea so short and understandable "$1 is interpolated into the argument string before gsub is run..."
Nakilon