将哈希转换为对象 [英] 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"}>
请参见@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?
推荐答案
您需要添加递归性:
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'}})
# => #<Hashit:0x007fa6029f4f70 @a="123r", @b=#<Hashit:0x007fa6029f4d18 @c="sdvs">>
这篇关于将哈希转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文