开发者

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

开发者 https://www.devze.com 2023-04-04 08:29 出处:网络
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 lo

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 t开发者_如何学Gohe SPAM we are getting hit with.

Examples:

r+kldslkadslkadslk@site.com .. true
r+123123312@site.com .. true
vigraaaa@site.com .. 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


This will match:

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

Examples:

>> 'r+kldslkadslkadslk@site.com' =~ /^r\+.*@site.com$/ #=> 0
>> 'vigraaaa@site.com' =~ /^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:

>> !!('vigraaaa@site.com' =~ /^r\+.*@site.com$/) #=> false
>> !!('r+kldslkadslkadslk@site.com' =~ /^r\+.*@site.com$/) #=> true


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.)


If you don't want to use an "!!" operator:

!!("foo" =~ /^f/)

you could use a ternary operator (might look more obvious):

"foo" =~ /^f/ ? true : false


You can use the '===' operator as well

/f/ === 'foo' #=> true

/f/ === 'bat' #=> false

Note: The regex part is on the left:

/YOUR_REGEX/ === 'YOUR_STRING'


Regexp#match? was added to Ruby-2.4.0. See Regexp#match documentation.

irb(main):001:0> "ack!".match? /a(b|c)/
=> true
irb(main):002:0> "add".match? /a(b|c)/
=> false
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号