Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you put a variable in a regexp?

I'm trying to validate wether a Model.category equals any existing Category name

unless Category.exists?(:name => self.category.downcase)

I had to put downcase in this to ensure all of them were downcased so they could match up as strings. But its a big server hit to update the attribute before_save, and I was thinking of just matching them via regexp. Something like this

unless Category.exists?(:name => /#{self.category}/ }

Is there something like that possible? Or is there a better way to do this?

like image 879
Trip Avatar asked Sep 12 '10 22:09

Trip


1 Answers

Yep, you can use variable interpolation in a regex.

>> s = "thing"
=> "thing"
>> r = /#{s}/
=> /thing/
like image 152
mipadi Avatar answered Oct 12 '22 10:10

mipadi