【问题标题】:Simple Ruby 'or' question简单的红宝石“或”问题
【发布时间】:2011-05-24 04:29:30
【问题描述】:

在控制台中:

@user.user_type = "hello"
@user.user_type == "hello"
  true
@user.user_type == ("hello" || "goodbye")
  false

如何编写最后一条语句,以便检查@user.user_type 是否包含在两个字符串之一中?

【问题讨论】:

    标签: ruby-on-rails ruby conditional


    【解决方案1】:
    ["hello", "goodbye"].include? @user.user_type
    

    【讨论】:

    • 我得到未定义的方法包括?对于[“应用程序/jpg”,“应用程序/png”]。我做错了什么?
    • 其实就是“包含?”。但是@sscirrus,您应该查看文档:ruby-doc.org/core/classes/Enumerable.html
    • 非常感谢 Tokland。我一直在寻找正确的来源,但谷歌搜索了几分钟没有找到它。 include? 工作正常。 +1!
    • 糟糕,今天早上只有一杯咖啡 8)
    • 如果您好奇,编程语言的创建者更喜欢第二人称单数或第三人称复数而不是第三人称单数。
    【解决方案2】:

    Enumerable#include? 是惯用且简单的方法,但作为旁注,让我向您展示一个非常琐碎的扩展,(我想)它会取悦 Python 粉丝:

    class Object
      def in?(enumerable)
        enumerable.include?(self)
      end
    end
    
    2.in? [1, 2, 3]  # true
    "bye".in? ["hello", "world"] # false   
    

    有时(实际上是大多数时候)询问对象是否在集合中比反之询问在语义上更合适。现在您的代码如下所示:

    @user.user_type.in? ["hello", "goodbye"]
    

    顺便说一句,我想你想写的是:

    @user.user_type == "hello" || @user.user_type == "goodbye"
    

    但我们程序员天生懒惰,所以最好使用Enumerable#include? 和朋友。

    【讨论】:

    • 太棒了。这个答案中有很多有价值的信息。
    猜你喜欢
    • 2011-05-10
    • 2013-01-18
    • 2016-03-23
    • 2011-01-09
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多