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:
- you have an array of objects
- you need a hash where the key is one of the object’s attributes and value is a different attribute (of the same object)
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}