这是我的杂烩:
tempData = {"a" => 100, "here" => 200, "c" => "hello"}
我需要通过如下方法访问哈希键:
tempData.a #100
tempData.here # 200
这是我的杂烩:
tempData = {"a" => 100, "here" => 200, "c" => "hello"}
我需要通过如下方法访问哈希键:
tempData.a #100
tempData.here # 200
你可以把你的杂烩包成OpenStruct:
require 'ostruct'
tempData = {"a" => 100, "here" => 200, "c" => "hello"}
os = OpenStruct.new tempData
os.a #=> 100
os.here #=> 200
如果你真的想,你也可以给Hash
级打补丁,但我建议你不要这么做:
class Hash
def method_missing(m, *args, &blk)
fetch(m) { fetch(m.to_s) { super } }
end
end
tempData = {"a" => 100, "here" => 200, "c" => "hello"}
tempData.a #=> 100
Update:在我的personal extensions library中,我添加了Hash#to_ostruct方法.这将递归地将哈希转换为包含所有嵌套哈希的OpenStruct
.