Looping over Ruby hash and filtering using each method
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 statemen开发者_Go百科t 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 want to filter out the element whose key is "three" for instance:
hash.reject {|key ,value| key == "three" }.each{...}
That works with any condition.
Only a little variant:
self.board.each { |position, piece|
next unless piece == 1
puts position
}
Instead of a if/end the each-loop will skip over the items you are not interested in.
精彩评论