2014-02-26 90 views
0

什麼是最簡單的方法:如果你有哈希散列如何刪除第一哈希值 - 紅寶石

{"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 ...

回答

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}} 
+0

我永遠不會要求我提出的答案是「優雅」。當然,優雅,像美麗,是在旁觀者的眼中。 –

+0

@CarySwoveland我同意一個觀點......這可能是一個長時間的討論,所以我已經改寫了我的句子。 –

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 
+0

馬是變量。我更新了我的問題。並感謝您的回答! – necker

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}} 
+0

馬是一個變量。我更新了我的問題。並感謝您的回答。 – necker

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

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}} 
1

一種方法是使用Hash#merge的形式,該形式使用塊來確定th存在於兩個哈希中的密鑰的e值被合併:

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 } }