创建嵌套哈希 - Ruby

use*_*731 0 ruby hash nested

我有两个唯一的散列,我想编写一个代码来从这两个创建单个嵌套散列。我知道可以手动创建嵌套哈希,但我更愿意编写代码来做到这一点。

cats = {"name" => "alpha", "weight" => "10 pounds"}
dogs = ("name" => "beta", "weight"=>"20 pounds"}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我的嵌套哈希类似于:

pets = {"dogs"=>{"name"=>"beta", "weight"=>"20 pounds"}, "cats"=>{"name"=>"alpha", "weight"=>"10 
pounds"}}
Run Code Online (Sandbox Code Playgroud)

如果有人可以分解代码为我完成上述操作,我将不胜感激。谢谢!!

roh*_*t89 5

你可以像这样轻松地做到这一点。

pets = {"dogs"=>dogs, "cats"=>cats}
Run Code Online (Sandbox Code Playgroud)

输出:

{"dogs"=>{"name"=>"beta", "weight"=>"20 pounds"}, "cats"=>{"name"=>"alpha", "weight"=>"10 pounds"}}
Run Code Online (Sandbox Code Playgroud)