我正在尝试检测电子邮件地址是否不是两个域之一,但我在使用 ruby 语法时遇到了一些问题。我目前有这个:
if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
#Do Something
end
这是条件的正确语法吗?
我正在尝试检测电子邮件地址是否不是两个域之一,但我在使用 ruby 语法时遇到了一些问题。我目前有这个:
if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
#Do Something
end
这是条件的正确语法吗?
而不是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")
这可能更容易阅读,因为||
不必用!
.
如果添加更多域,那么重复性email_address.end_with?
会很快变得无聊。选择:
if ["@domain1.com", "@domain2.com"].none?{|domain| email_address.end_with?(domain)}
#do something
end
我忘了end_with?
接受多个参数:
unless email_address.end_with?("@domain1.com", "@domain2.com")
#do something
end
怎么样:
(!email_address[/@domain[12]\.com\z/])