2 if语句中的条件

Dea*_*ean 12 ruby

我试图检测电子邮件地址是不是两个域之一,但我有一些ruby语法的麻烦.我目前有这个:

if ( !email_address.end_with?("@domain1.com") or !email_address.end_with?("@domain2.com"))
  #Do Something
end
Run Code Online (Sandbox Code Playgroud)

这是条件的正确语法吗?

Mic*_*ski 31

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

if ( !email_address.end_with?("@domain1.com") && !email_address.end_with?("@domain2.com"))
  #Do Something
end
Run Code Online (Sandbox Code Playgroud)

通过使用or,如果任一条件为真,则整个条件仍然是假的.

请注意,我使用的是&&代替and,因为它具有更高的优先级.这里详细介绍了详细信息

来自评论:

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

unless email_address.end_with?("@domain1.com") || email_address.end_with?("@domain2.com")
Run Code Online (Sandbox Code Playgroud)

这可能更容易阅读,因为双方都||不必被否定!.

  • 或者,等效地:除非email_address.end_with?("@ domain1.com")|| email_address.end_with?( "@ domain2.com") (2认同)

ste*_*lag 6

如果添加更多域,那么重复性email_address.end_with?就会变得非常快.替代方案:

if ["@domain1.com", "@domain2.com"].none?{|domain| email_address.end_with?(domain)}
  #do something
end
Run Code Online (Sandbox Code Playgroud)


ste*_*lag 5

我忘记了end_with?多个论点:

unless email_address.end_with?("@domain1.com", "@domain2.com")
 #do something
end
Run Code Online (Sandbox Code Playgroud)