supersize
supersize

Reputation: 14773

Print keys for certain value

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

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

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

Ilya
Ilya

Reputation: 13477

You can use map and compact methods:

hash.map { |k, v| k if v }.compact

Upvotes: 1

sawa
sawa

Reputation: 168091

hash.each do |k, v|
  puts k if v == true
end

Upvotes: 3

Albin
Albin

Reputation: 3012

It is as simple as:

hash.each do |k,v|
  puts k if v
end

Upvotes: 0

Related Questions