Convert A Hash To A Struct In Ruby

Posted By Weston Ganger

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.

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:

Article Topic:Software Development - Ruby / Rails

Date:January 24, 2017