Convert a hash into a struct
Solution 1:
If you already have a struct defined, and you want to instantiate an instance with a hash:
Person = Struct.new(:first_name, :last_name, :age)
person_hash = { first_name: "Foo", last_name: "Bar", age: 29 }
person = Person.new(*person_hash.values_at(*Person.members))
=> #<struct Person first_name="Foo", last_name="Bar", age=29>
Solution 2:
If it doesn't specifically have to be a Struct
and instead can be an OpenStruct
:
pry(main)> require 'ostruct'
pry(main)> s = OpenStruct.new(h)
=> #<OpenStruct a=1, b=2>
pry(main)> puts s.a, s.b
1
2
Solution 3:
Since Hash key order is guaranteed in Ruby 1.9+:
Struct.new(*h.keys).new(*h.values)
Solution 4:
This is based on @elado's answer above, but using the keyword_init
value (Struct Documentation)
You could simply do this:
Person = Struct.new(:first_name, :last_name, :age, keyword_init: true)
person_hash = { first_name: "Foo", last_name: "Bar", age: 29 }
person = Person.new(person_hash)
=> #<struct Person first_name="Foo", last_name="Bar", age=29>