Code Like Zell

How to use ruby variables inside regular expressions

In this case it is best to learn by example, fire up irb and enter:

str = "this string has ruby in it"
re = 'ruby'
str =~ /#{re}/

The 16 that gets returned is the location of the first matching character, ‘r’. You can also use this with gsub, for instance:

str = "uhhhh, I don't have a good example"
speech_correcting_reg_ex = 'uh+,?\s?'
str.gsub!(/#{speech_correcting_reg_ex}/,'')

And just like that, we have proper English. Should there be a comma there?

Thanks for reading, now find something to do at  GoLark.com


1 Comment

“Constructing Regexp objects from strings” would be a more appropriate title. This is handy for when you have several common patterns that you would like to combine in different ways. At the time, I thought you could only combine patterns by using strings in the Regexp constructor. But:

a = /ruby/
a.class –> Regexp
/#{a}/.class –> Regexp

So we can combine Regexp objects inside // to construct a new Regexp.

Just to sum up:
a = /ruby/
b = /on rails/

str = “this string has ruby on rails in it”
str =~ /#{a}\s#{b}/ –> true

Posted by lou on 26 June 2008 @ 3am

Leave a Comment

How to use javascript to hijack the enter key