The Ruby %r{} expression
Tonight I was reading over some Ruby code in a gem I’m currently using and came across this line:
1
2
string = mode.to_s
string.gsub!(%r{(^.)|(_.)}) { |m| m[m.length-1,1].upcase }
Two things struck me about that second line. For one I’ve never used gsub and passed it a block, thats cool. And two, what is %r{} ? I’ve never seen that before. It turns out that in Ruby, the /…/ or %r… literals, and using the Regexp.new constructor are all the same thing. All ways of created a regular expression. I still think I prefer the look of the simple slashes /…/ though.
Comments