【问题标题】:Ruby each iterator returning array rather than booleanRuby 每个迭代器返回数组而不是布尔值
【发布时间】:2013-11-10 21:27:23
【问题描述】:

我有如下代码(为了便于阅读,已截断/转述)

def board_check?
  @board.each {|row| check_row_for_truth_conditions(row)}
end

def check_row_for_truth_conditions(row)
  return true if row.include("foo")
  false
end

现在每个迭代器的隐式返回总是它正在迭代的集合。 IE;我得到了数组,不是真假。如果我不重构并执行以下操作,它将按预期工作。但是我在很多地方都使用了 check_row_for_truth_conditions(而且它更长),所以想重构它

def board_check?
  @board.each do |row| 
    return true if row.include("foo")
    false
  end
end

【问题讨论】:

  • 我想通了。我可以通过使用任何东西得到我想要的东西吗?而不是每个。所以@board.any? {|row| check_row_for_truth_conditions(row)}

标签: ruby each enumerable


【解决方案1】:

一个选项是:

def board_check?
  @board.any? {|row| row.include("foo") }
end

【讨论】:

    【解决方案2】:

    传递给每个(false)的块的返回值被丢弃。显式返回有效,因为它从方法返回,而不是从块返回。你反而想要:

    def board_check?
      @board.each do |row| 
        return true if row.include("foo")
      end
      return false
    end
    

    但你真的想使用any?

    def board_check?
      @board.any? do |row| 
        row.include("foo")  # or perhaps check_row_for_truth_conditions(row)
      end
    end
    

    此外,您的 check_row_for_truth_conditions 可以简化为:

    def check_row_for_truth_conditions(row)
      row.include("foo")
    end
    

    不需要显式返回true/false

    【讨论】:

    • 谢谢!发现我应该在你输入的时候使用任何权利:) 我会尽快接受
    猜你喜欢
    • 2011-09-13
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多