Tonight I was reading over some Ruby code in a gem I’m currently using and came across this line:
1 string = mode.to_s 2 string.gsub!(%r{(^.)|(_.)}) {|m| m[m.length-1,1].upcase } 3
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.
{ 4 comments… read them below or add one }
I totally agree, and that is the only ugly “Perl-like” thing about ruby, that sometimes makes me mad. But nobody is perfect, right?
I meant and that is NOT the only “Perl-like” thing about ruby, that sometimes makes me mad.
It’s useful when running regexes over paths. %r{a/b/c} vs /a\/b\/c/
Nice tip, thanks for sharing