Reputation: 1696
I would like to extract hash key values to an array when a condition is met. For example, with hash h I want to extract the keys where the values are "true":
h = { :a => true, :b => false, :c =>true }
I've come up with this:
h.map {|k,v| k if v==true} - [nil]
Any alternatives?
Upvotes: 3
Views: 6891
Reputation: 4980
You can also do
s = {}
h.each do |k,v|
s[k] = v if v==true
end
Upvotes: 0
Reputation: 23556
h.select { |_, v| v }.keys
Will do the same, but in more readable way.
Upvotes: 15