Reputation: 8986
I have an object that has attributes name
and data
, among others. I want to create a hash that uses the name as the key and the data (which is an array) as the value. I can't figure out how to reduce the code below using map
. Is it possible?
def fc_hash
fcs = Hash.new
self.forecasts.each do |fc|
fcs[fc.name] = fc.data
end
fcs
end
Upvotes: 20
Views: 13438
Reputation: 45
With Ruby 2.1 and onward, you could also use Array#to_h
self.forecasts.to_h { |forecast| [forecast.name, forecast.data] }
Upvotes: 0
Reputation: 3205
I always use inject
or reduce
for this:
self.forecasts.reduce({}) do |h,e|
h.merge(e.name => e.data)
end
Upvotes: 3
Reputation: 115541
def fc_hash
forecasts.each_with_object({}) do |forecast, hash|
hash[forecast.name] = forecast.data
end
end
Upvotes: 14
Reputation: 15605
Use Hash[]
:
Forecast = Struct.new(:name, :data)
forecasts = [Forecast.new('bob', 1), Forecast.new('mary', 2)]
Hash[forecasts.map{|forecast| [forecast.name, forecast.data]}]
# => {"mary"=>2, "bob"=>1}
Upvotes: 24