How to determine if there is a match an return true or false in rails?

AnApprentice picture AnApprentice · Sep 9, 2011 · Viewed 23.4k times · Source

I want to create a test that returns either true or false for email handling.

For now, if the email address starts with r+ then it's true otherwise it's false. This will help our server ignore a lot of the SPAM we are getting hit with.

Examples:

[email protected] .. true
[email protected] .. true
[email protected] .. FALSE

What's the most efficient way to handle this with Rails/ruby/regex?

Thanks

GOAL

Is a one liner in rails/ruby with:

ABORT if XXXXX == 0

Answer

Michael Kohl picture Michael Kohl · Sep 9, 2011

This will match:

/^r\+.*@site.com$/

Examples:

>> '[email protected]' =~ /^r\+.*@site.com$/ #=> 0
>> '[email protected]' =~ /^r\+.*@site.com$/ #=> nil

Since everything that isn't nil or false is truthy in Ruby, you can use this regex in a condition. If you really want a boolean you can use the !! idiom:

>> !!('[email protected]' =~ /^r\+.*@site.com$/) #=> false
>> !!('[email protected]' =~ /^r\+.*@site.com$/) #=> true