Ruby $1 vs \1
I was attempting to take some unordered SQL values and order them today with a single line of ruby. Essentially, the sql values look like (1, "value1"), (2, "value2"), and so on. I started out with this, but I couldn’t for the life of me figure out why the gsub statement wouldn’t work.
INCORRECT: ruby -e " y = []; STDIN.readlines.each { |x| if x=~/^\(/; y[x.gsub(/\(([0-9]+),.*/, $1.to_s).to_i]=x; end }; y.each { |z| puts z if ! z.nil?; } " < unordered.sql > ordered.sql
The weird thing is, if I take the if x=~ /^\(/; statement out, the code works. So, someone in #ruby-lang on Freenode reminded me that I need to use '\1' instead of $1.to_s in this case. I ran into this once before, however, I’m still not 100% sure on what the exact rules are for the syntax. So, this was the correct way to do it.
CORRECT: ruby -e " y = []; STDIN.readlines.each { |x| if x=~/^\(/; y[x.gsub(/\(([0-9]+),.*/, '\1').to_i]=x; end }; y.each { |z| puts z if ! z.nil?; } " < unordered.sql > ordered.sql
Trackbacks
Use this link to trackback from your own site.






