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(hash) hash.each do |k,v| self.instance_variable_set("@#{k}", 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
But problem is, i also want to convert nested hash objects. but couldn't make it.
h = Hashit.new({a: '123r', b: {c: 'sdvs'}}) => #<Hashit:0x00000006516c78 @a="123r", @b={:c=>"sdvs"}>
see @b={:c=>"sdvs"}
this part in output. I want also to convert it to object. is it possible if yes then how?
You can use OpenStruct http://ruby-doc.org/stdlib-2.0.0/libdoc/ostruct/rdoc/OpenStruct.html
user = OpenStruct.new({name: "Jimmy Cool", age: "25"}) user.name #Jimmy Cool user.age #25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With