user13350731
user13350731

Reputation: 97

Creating nested hash - Ruby

I have two unique hashes and I want to write a code to create a single nested hash from those two. I understand one can create a nested hash manually, but I'd rather be able to write code to do that.

cats = {"name" => "alpha", "weight" => "10 pounds"}
dogs = ("name" => "beta", "weight"=>"20 pounds"}

Ideally my nested hash would resemble:

pets = {"dogs"=>{"name"=>"beta", "weight"=>"20 pounds"}, "cats"=>{"name"=>"alpha", "weight"=>"10 
pounds"}}

I'd really appreciate it if someone could break down the code to do the above for me. Thank you!!

Upvotes: 0

Views: 76

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

Just for fun, you can also get all the local variables automatically and save them into a hash:

cats = {"name" => "alpha", "weight" => "10 pounds"}
dogs = {"name" => "beta", "weight"=>"20 pounds"}

puts binding.local_variables.map{|var| [var.to_s, binding.local_variable_get(var)] }.to_h
# {"cats"=>{"name"=>"alpha", "weight"=>"10 pounds"}, "dogs"=>{"name"=>"beta", "weight"=>"20 pounds"}}

But please the other answer instead.

Upvotes: 0

rohit89
rohit89

Reputation: 5773

You can do it easily like this.

pets = {"dogs"=>dogs, "cats"=>cats}

Output:

{"dogs"=>{"name"=>"beta", "weight"=>"20 pounds"}, "cats"=>{"name"=>"alpha", "weight"=>"10 pounds"}}

Upvotes: 5

Related Questions