最简单的方法是什么:
{"Wednesday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}},
"Thursday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}}}
到此?
{"Wednesday"=>{"9.0"=>1, "10.0"=>1},
"Thursday"=>{"9.0"=>1, "10.0"=>1}}
我已经在我的控制台里苦苦挣扎了2个小时。
感谢任何答案!
P.S。马是一个变量,如:FrenchStalion,BelgianStalion,Lipicanec ......
答案 0 :(得分:2)
这个怎么样。
hash = {"Wednesday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}},
"Thursday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}}}
a ={}
hash.each do |k,v|
a[k]=v.values.first
end
答案 1 :(得分:1)
这样做
a = {"Wednesday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}},
"Thursday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}}}
d = {}
a.each { |k,v| d[k] = v["Horse"] }
puts d
答案 2 :(得分:1)
我会做
hash = {"Wednesday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}},
"Thursday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}}}
hash.each_with_object({}) { |(k,v),h| h[k] = v['Horse']}
# => {"Wednesday"=>{"9.0"=>1, "10.0"=>1}, "Thursday"=>{"9.0"=>1, "10.0"=>1}}
<强>更新强>
hash.each_with_object({}) { |(k,v),h| h[k] = v.shift.last}
# => {"Wednesday"=>{"9.0"=>1, "10.0"=>1}, "Thursday"=>{"9.0"=>1, "10.0"=>1}}
答案 3 :(得分:1)
Hash[]
方法对于构造哈希值非常方便:
hash = {
"Wednesday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}},
"Thursday"=>{"Horse"=>{"9.0"=>1, "10.0"=>1}}
}
x = "Horse"
Hash[
hash.collect do |k, v|
[ k, v[x] ]
end
]
# => {"Wednesday"=>{"9.0"=>1, "10.0"=>1}, "Thursday"=>{"9.0"=>1, "10.0"=>1}}
答案 4 :(得分:1)
功能性样式解决方案(无需修改原始哈希或使用额外变量 - 对我来说看起来优雅的解决方案)
hash.reduce({}) { |acc, (k, v)| acc.merge(Hash[k, *v.values]) }
# => {"Wednesday"=>{"9.0"=>1, "10.0"=>1}, "Thursday"=>{"9.0"=>1, "10.0"=>1}}
答案 5 :(得分:1)
一种方法是使用Hash#merge的形式,它使用一个块来确定合并的两个哈希中存在的键的值:
h = { "Wednesday"=>{ "Horse"=>{ "9.0"=>1, "10.0"=>1 } },
"Thursday" =>{ "Horse"=>{ "9.0"=>1, "10.0"=>1 } } }
key = "Horse"
h.merge(h) { |*_,g| g[key] }
#=> { "Wednesday"=>{ "9.0"=>1, "10.0"=>1 },
# "Thursday" =>{ "9.0"=>1, "10.0"=>1 } }