ctaymor
ctaymor

Reputation: 175

In a set of hashes, how to access all elements of one key as enumerable object?

I have a nested hash inside a set, in my rails app, and I'm trying to access all the values of one key in an enumerable way.

So I have a set which looks like this (not the actual names of my keys and values)

my_set=[{:foo=>"lion", :boolean1=>true, :boolean2=>false, :boolean3=>true},
         {:foo=>"monkey", :boolean1=>false, :boolean2=>true, :boolean3=>true},
         {:foo=>"elephant", :boolean1=>false, :boolean2=>true, :boolean3=>true}
         ]

I want to be able to iterate over all the values of foo. Is there a better way to do it than as follows?

foo_array=[]
my_set.each do |hash|
  foo_array<<hash[:foo]
end

I haven't been able to find anything on accessing all the values of :foo in my set, only on accessing individual elements in the nested enumerables, which I know how to do. Thank you.

Upvotes: 0

Views: 92

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

First, your definition for my_set isn't valid.

Fixing that, I'd use:

my_set=[
  {:foo=>"lion", :boolean1=>true, :boolean2=>false, :boolean3=>true},
  {:foo=>"monkey", :boolean1=>false, :boolean2=>true, :boolean3=>true},
  {:foo=>"elephant", :boolean1=>false, :boolean2=>true, :boolean3=>true}
]

foo_array = my_set.map{ |h| h[:foo] } # => ["lion", "monkey", "elephant"]

Your code works fine too though:

foo_array=[]
my_set.each do |hash|
  foo_array<<hash[:foo]
end
foo_array # => ["lion", "monkey", "elephant"]

It's just a different way of doing it.

Upvotes: 1

lurker
lurker

Reputation: 58244

I think the simplest way would be this:

foo_array = my_set.map { |hash| hash[:foo] }

Upvotes: 2

Related Questions