Regexp.union say goodbye to join('|')
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 Ruby | no comments | atom
Trackbacks
Use the following link to trackback from your own site:
http://www.rubyfindings.com/trackbacks?article_id=regexp-union-say-goodbye-to-join&day=16&month=06&year=2008