Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a hash into a struct

Tags:

ruby

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
like image 549
alf Avatar asked Aug 14 '12 23:08

alf


3 Answers

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>
like image 103
elado Avatar answered Nov 09 '22 04:11

elado


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
like image 32
Dave Newton Avatar answered Nov 09 '22 03:11

Dave Newton


Since Hash key order is guaranteed in Ruby 1.9+:

Struct.new(*h.keys).new(*h.values)
like image 56
Phrogz Avatar answered Nov 09 '22 03:11

Phrogz