目标:OpenStruct 对象的值应打印为散列而不是对象
可能的解决方案:覆盖 OpenStruct 类的 getter
MyOpenStruct
覆盖和的。new
_to_h
[]
OpenStruct
class MyOpenStruct < OpenStruct
def initialize(object=nil)
@table = {}
@hash_table = {}
if object
object.each do |k,v|
if v.is_a?(Array)
other = Array.new()
v.each { |e| other.push(self.class.new(entry)) }
v = other
end
@table[k.to_sym] = (v.is_a?(Hash) ? self.class.new(v) : v)
@hash_table[k.to_sym] = v
new_ostruct_member(k)
end
end
end
def [](val)
@hash_table[val.to_sym]
end
end
但是压倒一切[]
并没有任何区别。例如
irb(main):007:0> temp = MyOpenStruct.new({"name"=>"first", "place"=>{"animal"=>"thing"}})
=> #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">>
irb(main):008:0> temp.name
=> "first"
irb(main):009:0> temp.place
=> #<MyOpenStruct animal="thing">
irb(main):010:0> temp["place"]
=> {"animal"=>"thing"}
irb(main):011:0> temp[:place]
=> {"animal"=>"thing"}
irb(main):012:0> temp
=> #<MyOpenStruct name="first", place=#<MyOpenStruct animal="thing">>
只有当我使用[]
哈希访问密钥时才会返回!
我该如何纠正这个?