I am trying to convert hash and nested hashes to objects.
so far first hash object is converted successfully by this code:
class Hashit
def initialize(
You could check the type on v
when you initialize the object and call new
to get a new Hashit
when it is a another hash.
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
and the resulting snippet from before would be:
h = Hashit.new({a: '123r', b: {c: 'sdvs'}})
=> #>