Ruby Findings

digging for gems

Regexp.union say goodbye to join('|')

Posted by Bill Marquette Tue, 17 Jun 2008 04:09:00 GMT

I’m feeling kind of dumb tonight. I must have read the little (and I do mean little) section on the Regexp class in my Ruby in a Nutshell book a billion times now (if that doesn’t say stupid, I dunno what does) and somehow every time I’ve missed this little beauty.

A little Regexp.union love converts this:

@words=["important","monkey","dancing"]

def highlight(input)
  input.gsub(/#{@words.join('|')}/, '*\0*')
end

puts highlight("I think it's important to have a dancing monkey in your bedroom.")
# => I think it's *important* to have a *dancing* *monkey* in your bedroom.

to this:

@words=["important","monkey","dancing"]

def highlight(input)
  input.gsub(Regexp.union(*@words), '*\0*')
end

puts highlight("I think it's important to have a dancing monkey in your bedroom.")
# => I think it's *important* to have a *dancing* *monkey* in your bedroom.

Posted in | no comments |