12

我正在尝试检测电子邮件地址是否不是两个域之一,但我在使用 ruby​​ 语法时遇到了一些问题。我目前有这个:

if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
  #Do Something
end

这是条件的正确语法吗?

4

4 回答 4

31

而不是or这里,你想要一个逻辑&&(和),因为你试图找到既不匹配的字符串。

if ( !email_address.end_with?("@domain1.com") && !email_address.end_with?("@domain2.com"))
  #Do Something
end

通过使用or,如果任一条件为真,则整个条件仍为假。

请注意,我使用的是&&代替and,因为它具有更高的优先级。细节在这里得到了很好的概述

从评论:

unless您可以使用with 逻辑或构建等效条件||

unless email_address.end_with?("@domain1.com") || email_address.end_with?("@domain2.com")

这可能更容易阅读,因为||不必用!.

于 2013-01-19T20:01:09.357 回答
6

如果添加更多域,那么重复性email_address.end_with?会很快变得无聊。选择:

if ["@domain1.com", "@domain2.com"].none?{|domain| email_address.end_with?(domain)}
  #do something
end
于 2013-01-19T20:45:15.480 回答
5

我忘了end_with?接受多个参数:

unless email_address.end_with?("@domain1.com", "@domain2.com")
 #do something
end
于 2013-01-20T00:08:24.037 回答
3

怎么样:

(!email_address[/@domain[12]\.com\z/])
于 2013-01-19T20:10:36.967 回答