João Daniel
João Daniel

Reputation: 8986

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

Upvotes: 20

Views: 13438

Answers (5)

Yann
Yann

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

bheeshmar
bheeshmar

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

Abid
Abid

Reputation: 7227

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

Upvotes: 1

apneadiving
apneadiving

Reputation: 115541

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

Upvotes: 14

Rein Henrichs
Rein Henrichs

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

Related Questions