The Ruby %r{} expression

by Irish on August 12, 2010

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 }

Christian Requena November 25, 2011 at 8:17 am

I totally agree, and that is the only ugly “Perl-like” thing about ruby, that sometimes makes me mad. But nobody is perfect, right? ;-)

Reply

Christian Requena November 25, 2011 at 8:18 am

I meant and that is NOT the only “Perl-like” thing about ruby, that sometimes makes me mad.

Reply

bronson October 9, 2012 at 2:20 pm

It’s useful when running regexes over paths. %r{a/b/c} vs /a\/b\/c/

Reply

Irish October 9, 2012 at 3:05 pm

Nice tip, thanks for sharing

Reply

Leave a Comment

Previous post:

Next post: