x = {:name => "John", :data => {:physical => {:age => 25, :weight => 150}}}
I'm looking to move the subattributes of data up one level (but not necessarily simply flatten all attributes). In this case, I essentially want to move the :physical attribute "up" one level.
I'm trying this
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}}
Since Ruby 1.9, hashes maintain the order in which they're stored.
We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
A Hash is a collection of key-value pairs. It is similar to an Array , except that indexing is done via arbitrary keys of any object type, not an integer index.
Try this:
x = x.merge(x.delete(:data))
I'd go after it this way:
x = {:name => "John", :data => {:physical => {:age => 25, :weight => 150}}}
x[:physical] = x.delete(:data)[:physical]
pp x #=> {:name=>"John", :physical=>{:age=>25, :weight=>150}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With