测试字符串是否不等于两个字符串中的任何一个

17

我刚开始学习 RoR,所以请耐心等待。我正在尝试编写一个带有字符串的 if 或语句。以下是我的代码:

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

我尝试了许多其他方法,使用括号和||,但似乎都不起作用。也许是因为我的JS背景...

如何测试一个变量是否不等于字符串一或字符串二?

2个回答

16

这是一个基础逻辑问题:

(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
只有当b==c时,(a==b) && (a==c)才可能为真。因此,由于您已经确定b != c,则if语句总是为假。 只是猜测,但您可能希望使用:
<% if controller_name != "sessions" and controller_name != "registrations" %>

15
<% unless ['sessions', 'registrations'].include?(controller_name) %>
或者
<% if ['sessions', 'registrations'].exclude?(controller_name) %>

NoMethodError:["",""]的数组未定义方法`exclude?' - Pat Myron
需要从Ruby on Rails的ActiveSupport中引用一些东西。require 'active_support/core_ext/enumerable' - Pat Myron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接