From: Mikel Lindsaar Date: 2007-07-20T13:47:45+09:00 Subject: Re: regex backreference weirdness... Instead of reinventing the wheel, you could always use the camelcase converter that Rails has and pull out what you need: http://api.rubyonrails.com/classes/ActiveSupport/CoreExtensions/String/Inflections.html Regards Mikel On 7/20/07, Kyle Schmitt wrote: > It all started with trying to convert some strings with underscores in > them, to camel case...and me thinking of regexes as sed regexes > > It looks like gsub saves back references, but only after the whole > method exits, so it can't use what it found. Is this right? > > Below is what I tried, which leads me up to the question of... what > would the _right_ way be of doing this? > > irb>"camel_case".gsub(/_(.)/,$1.upcase) > NoMethodError: undefined method `upcase' for nil:NilClass > from (irb):1 > #Which made me say Hu? it looks like a valid back reference to me... > #So I tried > "camel_case"=~/_(.)/ > irb>puts $1 > =>"c" > #ok really wierd... > irb>"camel_case".gsub(/_(.)/,$1.upcase) > =>"camelCase" > #Right, I'll buy that since $1 is still hanging around > irb>"camel_face".gsub(/_(.)/,$1.upcase) > =>"camelCase" > irb>"camel_face".gsub(/_(.)/,$1.upcase) > =>"camelFase" > #Ha ha! gsub DOES save a backreference... so why isn't this working?! :( > >