ruby 2 if 语句中的条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14418283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
2 Conditions in if statement
提问by Dean
I am trying to detect if the email address is not one of two domains but I am having some trouble with the ruby syntax. I currently have this:
我试图检测电子邮件地址是否不是两个域之一,但我在使用 ruby 语法时遇到了一些问题。我目前有这个:
if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
#Do Something
end
Is this the right syntax for the conditions?
这是条件的正确语法吗?
回答by Michael Berkowski
Rather than an orhere, you want a logical &&(and) because you are trying to find strings which match neither.
而不是or在这里,你想要一个合乎逻辑的&&(和),因为你正在努力寻找匹配哪些字符串既不。
if ( !email_address.end_with?("@domain1.com") && !email_address.end_with?("@domain2.com"))
#Do Something
end
By using or, if either condition is true, the whole condition will still be false.
通过使用or,如果任一条件为真,则整个条件仍为假。
Note that I am using &&instead of and, since it has a higher precedence. Details are well outlined here
请注意,我使用的是&&代替and,因为它具有更高的优先级。细节在这里得到了很好的概述
From the comments:
来自评论:
You can build an equivalent condition using unlesswith the logical or ||
您可以使用unless逻辑或||
unless email_address.end_with?("@domain1.com") || email_address.end_with?("@domain2.com")
This may be a bit easier to read since both sides of the ||don't have to be negated with !.
因为两侧,这可能是更容易阅读一点||不必与被否定你!。
回答by steenslag
If more domains are added, then the repetitive email_address.end_with?is getting boring real fast. Alternative:
如果添加了更多域,那么重复性email_address.end_with?会很快变得无聊。选择:
if ["@domain1.com", "@domain2.com"].none?{|domain| email_address.end_with?(domain)}
#do something
end
回答by steenslag
I forgot end_with?takes multiple arguments:
我忘了end_with?需要多个参数:
unless email_address.end_with?("@domain1.com", "@domain2.com")
#do something
end
回答by the Tin Man
How about:
怎么样:
(!email_address[/@domain[12]\.com\z/])

