ruby on rails - Create Hash iterating an array of objects

ID : 274351

viewed : 40

Tags : ruby-on-railsrubyruby-on-railsruby





Top 5 Answer for ruby on rails - Create Hash iterating an array of objects

vote vote

100

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} 
vote vote

85

def fc_hash  forecasts.each_with_object({}) do |forecast, hash|     hash[forecast.name] = forecast.data   end end 
vote vote

74

I always use inject or reduce for this:

self.forecasts.reduce({}) do |h,e|   h.merge(e.name => e.data) end 
vote vote

69

Hash[*self.forecases.map{ [fc.name, fc.data]}.flatten] 
vote vote

50

With Ruby 2.1 and onward, you could also use Array#to_h

self.forecasts.to_h { |forecast| [forecast.name, forecast.data] } 

Top 3 video Explaining ruby on rails - Create Hash iterating an array of objects







Related QUESTION?