Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert hash keys to array only if their values are set to true

Tags:

ruby

I'm trying to find an elegant and compact way to convert hash keys into array that contains only those that have true as value

example = {"foo" => true, "bar" => false, "baz" => true}

become

example = ["foo", "baz"]
like image 821
Federico Days Avatar asked Dec 21 '25 17:12

Federico Days


1 Answers

example = example.keys.select {|key| example[key].eql? true}

p example

output

["foo", "baz"]
like image 63
Rajagopalan Avatar answered Dec 23 '25 06:12

Rajagopalan