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

If you're in Rails, there's a starts_with? method on strings:

"foo".starts_with?('f') # => true
"foo".starts_with?('g') # => false

Outside of Rails, regexes are a reasonable solution:

"foo" =~ /^f/ # => true
"foo" =~ /^g/ # => false

Because Ruby uses truthiness in if statements, if you do end up using regexes, you can just use the return value to switch:

if "foo" =~ /^f/
  puts "Was true!"
else
  puts "Was false!"
end

If you're writing a method and want to return a boolean result, you could always use the double bang trick:

def valid_email?
  !!("foo" =~ /^f/)
end

Rubular (rubular.com) is a good site for testing Ruby regexes pre-1.9. (1.9's regexes added things like lookahead.)


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