DavB
DavB

Reputation: 1696

Ruby hash keys to array conditional on hash value

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

Answers (2)

Kumar Akarsh
Kumar Akarsh

Reputation: 4980

You can also do

s = {}
h.each do |k,v|
   s[k] = v if v==true
end

Upvotes: 0

Hauleth
Hauleth

Reputation: 23556

h.select { |_, v| v }.keys

Will do the same, but in more readable way.

Upvotes: 15

Related Questions