werid, same expression yield different value when excuting two times in irb
irb(main):051:0> "ts_id < what"开发者_JS百科.gsub(/(=|<|>)\s?(\w+|\?)/,"#{$1} ?")
=> "ts_id > ?"
irb(main):052:0> "ts_id < what".gsub(/(=|<|>)\s?(\w+|\?)/,"#{$1} ?")
=> "ts_id < ?"
Can anyone enlighten me?
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.
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 < ?"
精彩评论