Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert hash to object

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?

like image 348
hehehuhu Avatar asked Nov 07 '14 20:11

hehehuhu


1 Answers

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 
like image 92
Samda Avatar answered Oct 23 '22 18:10

Samda