3

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?

2
  • map and select methods are aliases, so you can use one of them. Commented Feb 7, 2013 at 8:43
  • 2
    @sbagdat, to be precise, map and collect are aliases, not select. select does different job and in case of Hash returns different type: it returns Hash, while map/collect return Array. Commented Feb 7, 2013 at 9:01

2 Answers 2

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

Will do the same, but in more readable way.

Sign up to request clarification or add additional context in comments.

4 Comments

That's nice, thanks. However, to return an array you need to use to_a.
keys returns an Array. What else would it return?
It's a clever way but i am not sure it is a "more readable way".
Why not? Also this is more general case, as it will allow all "true" values, not only true (in Ruby, like in Scheme, anything except nil and false is true in condition, but 1 != true).
0

You can also do

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.