2013-10-31 29 views
-1

我有这样(截断/转述了可读性)红宝石每个迭代器返回数组而不是布尔

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 

眼下的每一个迭代器始终是它遍历集合隐含返回代码。即;我得到数组,不是真或假。如果我不重构并执行如下操作,它将按预期工作。不过我用的是check_row_for_truth_conditions在很多地方(这是更长的时间),所以想重构出来

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

我想通了。使用任何我可以得到我想要的?而不是每个。所以'@ board.any? {|行| check_row_for_truth_conditions(row)}' – user2892536

回答

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

+0

谢谢!想出我应该使用任何正确的,因为你正在打字:)我会尽快接受 – user2892536

2

一种选择是:

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