Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Hash iterating an array of objects

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
like image 408
João Daniel Avatar asked Apr 02 '13 18:04

João Daniel


1 Answers

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}
like image 184
Rein Henrichs Avatar answered Sep 27 '22 18:09

Rein Henrichs