-1

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
  • I figured it out. I can get what I want by using any? instead of each. So `@board.any? {|row| check_row_for_truth_conditions(row)}` – user2892536 Oct 31 '13 at 01:42

2 Answers2

3

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.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
3

One option is:

def board_check?
  @board.any? {|row| row.include("foo") }
end
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497