Rhs
Rhs

Reputation: 3318

Convert List of Objects to Hash

In Ruby, I have a list of objects called Things with an Id property and a value property.

I want to make a Hash that contains Id as the key and Value as the value for the cooresponding key.

I tried:

result = Hash[things.map { |t| t.id, t.value }]

where things is a list of Thing

But this did not work.

Upvotes: 0

Views: 1691

Answers (2)

steenslag
steenslag

Reputation: 80065

result = things.map{|t| {t.id => t.value } }

The content of the outer pair of curly brackets is a block, the inner pair forms a hash. However, if one hash is the desired result (as suggested by Cary Swoveland) this may work:

result = things.each_with_object({}){| t, h | h[t.id] = t.value}

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

class Thing
  attr_reader :id, :value
  def initialize(id, value)
    @id = id
    @value = value
  end
end

cat = Thing.new("cat", 9)
  #=> #<Thing:0x007fb86411ad90 @id="cat", @value=9> 
dog = Thing.new("dog",1)
  #=> #<Thing:0x007fb8650e49b0 @id="dog", @value=1> 

instances =[cat, dog]
  #=> [#<Thing:0x007fb86411ad90 @id="cat", @value=9>,
  #    #<Thing:0x007fb8650e49b0 @id="dog", @value=1>] 

instances.map { |i| [i.id, i.value] }.to_h
  #=> {"cat"=>9, "dog"=>1}

or, for Ruby versions prior to 2.0:

Hash[instances.map { |i| [i.id, i.value] }]
  #=> {"cat"=>9, "dog"=>1}

Upvotes: 2

Related Questions