)\s?(\w+|\?)/,"#{$1} ?"...">

Werid, the same expression gives a different meaning when requested twice in irb

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 someone enlighten me?

+4
source share
2 answers

The problem is that the $1 variable is interpolated into the argument string before gsub is executed, which means that the previous value of $1 is what is replaced by a character. Can you replace the second argument with '\1 ?' to get the intended effect.

+5
source
 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 a fresh starting irb where $1 was nil . This is because when using .gsub(...,..$1..) when calculating the "part to the right of , " $1 not generated by the "left part of , ".

Do this:

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

Or that:

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

All Articles