2013-06-01 38 views
9

我刚刚学习RoR,请耐心等待。我正在尝试写一个if或带有字符串的语句。这里是我的代码:测试字符串是否与两个字符串中的任何一个不相等

<% if controller_name != "sessions" or controller_name != "registrations" %> 

我试过很多其他方法,使用括号和||但似乎没有任何工作。也许是因为我的JS背景...

我该如何测试一个变量是不是等于字符串1还是字符串2?

回答

9

这是一个基本的逻辑问题:

(a !=b) || (a != c) 

永远是只要B = C真!一旦你记得在布尔逻辑

(x || y) == !(!x && !y) 

然后你可以找到你的出路在黑暗中。

(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 

为唯一的方法(A == B)& &(A == c)中是真实的是对于b ==℃。因此,既然你已经给出b!= c,那么if语句将始终为假。

只是猜测,但可能你想在

<% if controller_name != "sessions" and controller_name != "registrations" %> 
+0

摇滚!很好的解释,谢谢:) – PropSoft

13
<% unless ['sessions', 'registrations'].include?(controller_name) %> 

<% if ['sessions', 'registrations'].exclude?(controller_name) %> 
相关问题