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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With