"John", :data => {:physical => {:age => 25, :weight => 150}}} I want to...">

How to transfer attributes in Ruby hash "up" one level

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

I want to move the data sub-attributes one level (but it’s not necessary to just smooth out all the attributes). In this case, I essentially want to move: the physical attribute "up" one level.

I'm trying to do it

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

but i get ...

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

I'm looking for...

 => {:name=>"John", :physical => {:age=>25, :weight=>150}} 
+5
source share
2 answers

Try the following:

x = x.merge(x.delete(:data))
+7
source

I would go like this:

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
source

All Articles