Reputation: 14773
I have a hash that looks similar to:
hash = {key1: true, key2: false, key3: false, key4: true}
and I would like to iterate through the hash and print each key which has a true
value. The result should look like:
key1
key4
How am I going to do that? I tried:
hash.each do |k,v|
puts k if true
end
Upvotes: 0
Views: 1046
Reputation: 121000
While iterating is fine, the goal might be achieved in more rubyish manner:
hash.select { |_, v| v }.keys
or, if equality to true
(as an opposite to being just truthy) is significant:
hash.select { |_, v| v == true }.keys
To print the result out:
puts hash.select { |_, v| v == true }.keys
Further information on how Hash#select
works.
To print all the keys matched as “key1 and key4”:
puts hash.select { |_, v| v == true }.keys.join(' and ')
Upvotes: 5
Reputation: 13477
You can use map
and compact
methods:
hash.map { |k, v| k if v }.compact
Upvotes: 1