Вопрос

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.

Это было полезно?

Решение

I think the simplest way would be this:

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top