Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over Ruby hash and filtering using each method

Tags:

ruby

I have the following code:

self.board.each { |position, piece| 
    if piece == 'test'
      ...
    end
}

I was wondering if there is a way to filter what my hash loops over? Instead of placing the If statement inside it?

I tried the 'Select' method on the hash with the 'each' method but with no luck.

Thanks

like image 526
Thomas Buckley Avatar asked Aug 16 '11 21:08

Thomas Buckley


1 Answers

Your code is idiomatic; I don't see any way to improve its performance or clarity. You could use select for a "pre-filter" like so:

self.board.select{|a,b|b=='test'}.each do |position,piece|
  # Now you are only looking at "test" pieces...
end

But it will perform roughly two iterations of the loop (instead of just one) and isn't as clear as your code, in my opinion. The only minor improvement I could imagine is as follows:

self.board.each do |position,piece|
  next unless piece == 'test'
  # ...
end

This way you don't need another level of indentation for your "main" logic.

like image 82
maerics Avatar answered Sep 29 '22 11:09

maerics