ruby 测试字符串是否不等于两个字符串中的任何一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16870540/
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
Test if string is not equal to either of two strings
提问by PropSoft
I am just learning RoR so please bear with me. I am trying to write an if or statement with strings. Here is my code:
我只是在学习 RoR,所以请耐心等待。我正在尝试用字符串编写 if 或语句。这是我的代码:
<% if controller_name != "sessions" or controller_name != "registrations" %>
I have tried many other ways, using parentheses and ||but nothing seems to work. Maybe its because of my JS background...
我尝试了很多其他方法,使用括号,||但似乎没有任何效果。也许是因为我的 JS 背景...
How can I test if a variable is not equal to string one or string two?
如何测试变量是否不等于字符串一或字符串二?
采纳答案by Old Pro
This is a basic logic problem:
这是一个基本的逻辑问题:
(a !=b) || (a != c)
will always be true as long as b != c. Once you remember that in boolean logic
只要 b != c,就永远为真。一旦你在布尔逻辑中记住了
(x || y) == !(!x && !y)
then you can find your way out of the darkness.
然后你就可以找到走出黑暗的路了。
(a !=b) || (a != c)
!(!(a!=b) && !(a!=c)) # Convert the || to && using the identity explained above
!(!!(a==b) && !!(a==c)) # Convert (x != y) to !(x == y)
!((a==b) && (a==c)) # Remove the double negations
The only way for (a==b) && (a==c) to be true is for b==c. So since you have given b != c, the ifstatement will always be false.
(a==b) && (a==c) 为真的唯一方法是 b==c。因此,由于您已给出 b != c,该if语句将始终为假。
Just guessing, but probably you want
只是猜测,但可能你想要
<% if controller_name != "sessions" and controller_name != "registrations" %>
回答by zolter
<% unless ['sessions', 'registrations'].include?(controller_name) %>
or
或者
<% if ['sessions', 'registrations'].exclude?(controller_name) %>

