0

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!!

1
  • Unless you're set on string keys, cats = { name: "alpha", ... } is a shorter way of doing this. Then cats[:name] for example. Commented Oct 20, 2020 at 16:59

2 Answers 2

5

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"}}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.