2011-06-12 40 views
5
x = {:name => "John", :data => {:physical => {:age => 25, :weight => 150}}} 

我正在尋找將數據的子屬性向上移動一層(但不一定只是簡化所有屬性)。在這種情況下,我基本上希望將物理屬性「向上」移動一個級別。如何將紅寶石散列中的屬性「向上」移動一個級別

我想這

y = x[:data'] 
y.each{ |key| x[key] = y[key] } 

,但我得到...

x = x.except(:data) 
=> {:name=>"John", [:physical, {:age=>25, :weight=>150}]=>nil} 

我找...

=> {:name=>"John", :physical => {:age=>25, :weight=>150}} 

回答

7

試試這個:

x = x.merge(x.delete(:data)) 
+0

難道你不是指':data',而是':physical'嗎? – matt 2011-06-12 22:11:11

+0

是的,修復了答案。 – 2011-06-12 22:12:45

+2

或['merge!'](http://ruby-doc.org/core/classes/Hash.html#M000758)以避免額外複製。 – 2011-06-12 22:41:47

2

我會追隨它:

x = {:name => "John", :data => {:physical => {:age => 25, :weight => 150}}} 

x[:physical] = x.delete(:data)[:physical] 

pp x #=> {:name=>"John", :physical=>{:age=>25, :weight=>150}}