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(
If I understand the question correctly, this should do it:
class Hashit
def initialize(hash)
convert_to_obj(hash)
end
private
def convert_to_obj(h)
h.each do |k,v|
self.class.send(:attr_accessor, k)
instance_variable_set("@#{k}", v)
convert_to_obj(v) if v.is_a? Hash
end
end
end
h = Hashit.new( { a: '123r',
b: { c: 'sdvs', d: { e: { f: 'cat' }, g: {h: 'dog'} } } })
#=> #"sdvs", :d=>{:e=>{:f=>"cat"}, :g=>{:h=>"dog"}}},
# @c="sdvs", @d={:e=>{:f=>"cat"}, :g=>{:h=>"dog"}},
# @e={:f=>"cat"}, @f="cat", @g={:h=>"dog"}, @h="dog">
h.instance_variables
#=> [:@a, :@b, :@c, :@d, :@e, :@f, :@g, :@h]
Hashit.instance_methods(false)
#=> [:a, :a=, :b, :b=, :c, :c=, :d, :d=, :e, :e=, :f, :f=, :g, :g=, :h, :h=]
h.d
#=> {:e=>{:f=>"cat"}}
h.d = "cat"
h.d
#=> "cat"