【问题标题】:Test if string is not equal to either of two strings测试字符串是否不等于两个字符串中的任何一个
【发布时间】:2013-05-28 01:22:42
【问题描述】:

我只是在学习 RoR,所以请多多包涵。我正在尝试用字符串编写 if 或语句。这是我的代码:

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

我尝试了许多其他方法,使用括号和||,但似乎没有任何效果。可能是因为我的JS背景...

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

【问题讨论】:

    标签: ruby if-statement logic


    【解决方案1】:

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

    (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==c。所以既然你给了 b != c,if 语句将永远是错误的。

    只是猜测,但可能你想要

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

    【讨论】:

      【解决方案2】:
      <% unless ['sessions', 'registrations'].include?(controller_name) %>
      

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

      【讨论】:

      • NoMethodError: 未定义的方法“排除?”对于 ["", ""]:数组
      • 需要来自 Ruby on Rails require 'active_support/core_ext/enumerable'ActiveSupport 的一些东西
      猜你喜欢
      • 2022-06-19
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2021-11-28
      • 2022-11-16
      • 2020-07-02
      • 2011-02-27
      • 1970-01-01
      相关资源
      最近更新 更多