Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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}} 
like image 529
Newy Avatar asked Jun 12 '11 21:06

Newy


People also ask

Does Ruby hash maintain order?

Since Ruby 1.9, hashes maintain the order in which they're stored.

How do you combine hashes in Ruby?

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.

Do hashes have indexes Ruby?

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.


2 Answers

Try this:

x = x.merge(x.delete(:data))
like image 194
Michaël Witrant Avatar answered Oct 19 '22 19:10

Michaël Witrant


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}}
like image 20
the Tin Man Avatar answered Oct 19 '22 20:10

the Tin Man