Full Blog Post

Use a Ruby Hash as a Class Object

21 Mar 2016 · Ruby
Ruby hash

If you need, for whatever reason, to use a Ruby Hash like a class object, you can do it using this little trick:

class Hashit
  def initialize(hash)
    hash.each do |k,v|
      self.instance_variable_set("@#{k}", v.is_a?(Hash) ? Hashit.new(v) : v)
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
    end
  end
end

h = Hashit.new({a: '123r', b: {c: 'sdvs'}})

# h.a => '123r'
# h.b.c => 'sdvs'

It's simple but you could increase the functionality of this class adding the methods you need.

Any place where I can pick the code of this tip?

Yeah! Here you have the Github gist for this tip :smile:

About
About The Author

Iván González - Software Developer

Hi, my name is Iván (aka dreamingechoes). I'm a passionate software developer from the north of Spain, interested in all kind of technologies.

Leave a comment!