Rails

How To Convert A Hash To A Struct In Ruby

Posted by Weston Ganger on January 24, 2017

I needed a simple way to convert a hash into a Struct in my Rails app. It wasn’t readily obvious how to do so but the answer is pretty simple.


h = {name: 'Foobar', description: 'test'}

Struct.new(*h.keys).new(*h.values)

You could take this one step further and create a monkey patch like below if your using this method often:


Hash.class_eval do
  
  def to_struct(h)
    Struct.new(*h.keys).new(*h.values)
  end

end

My ruby gem rearmed-rb provides this monkey patch and many others. It is a collection for helpful methods and monkey patches that can be safely applied on an opt-in basis.


Related External Links:


Posted in Rails and Tagged with ruby hash struct 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts