如何在Ruby on Rails中动态地将哈希添加到另一个哈希?

时间:2017-12-10 20:40:42

标签: ruby-on-rails ruby hash

我对Ruby非常陌生,无法知道如何做到这一点。基本上我想要的是将这个PHP代码转换为Ruby代码:

$some_array = ['user_id' => 23, 'parent_id' => 24, ...];
$another_array[$some_array['parent_id']]['respuestas'][] = $some_array;

我一直试图弄清楚如何去做,并且已经阅读了有关此主题的几个问题,但无法找到合适的解决方案。上面的代码将在循环内部,因此$another_array[$some_array['parent_id']]['respuestas']内部会有多个项目,我不知道究竟有多少项,因为结果来自数据库。

请不要指向正确的方向,我会陷入其中:(

编辑:这是我试图"翻译"的实际PHP代码。进入Ruby

$comments = array();
foreach($ar as $item)
{
   $parent_array = get_some_array_back();
   $comments[$parent_array['parent_id']]['replies'][] = $item;
}

return $comments;

编辑2:这是来自两个阵列的数据:

 $item = {
   ["comment_id"=> 1, "comment_text" => "text", "parent_id" => null ],
   ["comment_id"=> 2, "comment_text" => "text2", "parent_id" => 1],
   ....
  }
 $parent_array = ["comment_id"=> 2, "commen_text" => "text", "parent_id"=>1]

所以我正在做的是我在$ comments数组中存储所有没有parent_id的注释,然后对其余的我进行数组搜索以查看parent_id是否为关键字我的$ comments数组。如果是,那么我将其添加为新索引"回复"所有注释的数组,作为父级。

1 个答案:

答案 0 :(得分:2)

首先得到父母,然后让孩子使用.map

#Data
comments = [{comment_id: 1, parent_id: nil, text: "parent 1 "}, {comment_id: 2, parent_id: nil, text: "parent 2 "}, {comment_id: 3, parent_id: 1, text: "reply for comment 1"}, {comment_id: 4, parent_id: 2, text: "reply for comment 2"}] 

# get the parents first
parents =  comments.map{ |comment| comment if comment[:parent_id] == nil }.compact

# children refers to each comment as parent with replies as children  

children = parents.map {|parent| parent.merge({children: comments.map {|children| children if children[:parent_id] == parent[:comment_id]}.compact })}

结果:

[{:comment_id=>1, :parent_id=>nil, :text=>"parent 1 ", :children=>[{:comment_id=>3, :parent_id=>1, :text=>"reply for comment 1"}]}, {:comment_id=>2, :parent_id=>nil, :text=>"parent 2 ", :children=>[{:comment_id=>4, :parent_id=>2, :text=>"reply for comment 2"}]}]