Today I Learned
by OneCode

How to convert an array of objects into a hash?

Today I worked a lot on specs. I found something that might be useful also for you.

Here is a problem:

So, you know how to do this? Here is a solution:

array_of_objects = [
  OpenStruct.new(name: 'object1', object_value: true), 
  OpenStruct.new(name: 'object2', object_value: false), 
  OpenStruct.new(name: 'object3', object_value: true)
]
array_of_objects.map{|item| [item.name, item.object_value]}.to_h

#=> {"object1"=>true, "object2"=>false, "object3"=>true}