我正在尝试检测电子邮件地址是否不是两个域中的一个,但我在ruby语法方面遇到了一些问题。我目前有这个:
if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
#Do Something
end
这是适用于条件的正确语法吗?
发布于 2013-01-19 20:01:09
在这里,您需要的不是or
,而是逻辑&&
(and),因为您正在尝试查找既不匹配也不匹配的字符串。
if ( !email_address.end_with?("@domain1.com") && !email_address.end_with?("@domain2.com"))
#Do Something
end
通过使用or
,如果任一条件为真,则整个条件仍为假。
请注意,我使用的是&&
而不是and
,因为它具有更高的优先级。详情请参阅well outlined here
从评论中:
您可以使用带有逻辑或||
的unless
来构建等效条件
unless email_address.end_with?("@domain1.com") || email_address.end_with?("@domain2.com")
这可能更容易阅读,因为!
不需要对||
的两边都求反。
发布于 2013-01-19 20:45:15
如果添加更多的域,那么重复的email_address.end_with?
很快就会变得无聊。替代方案:
if ["@domain1.com", "@domain2.com"].none?{|domain| email_address.end_with?(domain)}
#do something
end
发布于 2013-01-20 00:08:24
我忘了end_with?
有多个参数:
unless email_address.end_with?("@domain1.com", "@domain2.com")
#do something
end
https://stackoverflow.com/questions/14418283
复制