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}}
答案 0 :(得分:8)
试试这个:
x = x.merge(x.delete(:data))
答案 1 :(得分: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}}
答案 2 :(得分:0)
基于@ micha%c3%abl-witrant的回答,由于我需要在嵌套数组上使用此函数,因此以下函数以递归方式进行操作:
def levelUpAttribute(attr,myHash,parent = nil)
if myHash.is_a?(Hash)
#level up matching keys
myHash = myHash.merge(myHash.delete(attr) || {})
#recursion
myHash.each do |key, value|
myHash[key] = levelUpAttribute(attr,value,key)
end
end
myHash
end
x = levelUpAttribute(:data,x)