How can I convert a hash into a struct in ruby?
Given this:
h = { :a => 1, :b => 2 }
I want a struct such that:
s.a == 1
s.b == 2
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>
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
Since Hash key order is guaranteed in Ruby 1.9+:
Struct.new(*h.keys).new(*h.values)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With