質問

I have code like the following (truncated/paraphrased for readability)

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

Right now the implicit return of that each iterator is always the collection it is iterating over. ie; I get the array back, not true or false. If I don't refactor and do something like the following, it works as expected. However I use the check_row_for_truth_conditions in many places (and it is much longer), so would like to refactor it out

def board_check?
  @board.each do |row| 
    return true if row.include("foo")
    false
  end
end
役に立ちましたか?

解決

The return value of the block passed to each (false) is thrown away. The explicit return works because that returns from the method, not the block. You instead want:

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

But really you want to use any?:

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

Also, your check_row_for_truth_conditions can be simplified to just this:

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

No need for the explicit return true/false.

他のヒント

One option is:

def board_check?
  @board.any? {|row| row.include("foo") }
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top