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
Your code is idiomatic; I don’t see any way to improve its performance or clarity. You could use
selectfor a “pre-filter” like so: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:
This way you don’t need another level of indentation for your “main” logic.