alf alf - 2 years ago 79
Ruby Question

Convert a hash into a struct

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

Answer Source

If it doesn't specifically have to be a Struct and instead can be an OpenStruct:

pry(main)> require 'ostruct'
pry(main)> s =
=> #<OpenStruct a=1, b=2>
pry(main)> puts s.a, s.b
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download