0

我有这种情况:

skeleton = 
{
        "timeline" => 
        { 
            "data" => []
        }
}

template = 
{
        "A" => "",
        "B" => "",
        "C" => "",
}

从控制器中,我进行了一个查询,该查询返回了一个哈希数组:

@cdr = Cdr.select("start, end, clid")

然后我遍历数组并设置“模板”哈希字段,在最后一步中,我将此哈希附加到属于“骨架”哈希的数组:

@cdr.each do |cdr|
        template["A"] = cdr.start
        template["B"] = cdr.end
        template["C"] = cdr.clid
        skeleton["timeline"]["data"] << template
    end

所以预期的结果是:

skeleton = 
{
        "timeline" => 
        { 
            "data" => [
               {
               "A" => "sample1",
               "B" => "sample2",
               "C" => "sample3",
               },
               {
               "A" => "sample4",
               "B" => "sample5",
               "C" => "sample6",
               }
            ]
        }
}

但我得到的真正结果是:

skeleton = 
{
        "timeline" => 
        { 
            "data" => [
               {
               "A" => "sample1",
               "B" => "sample2",
               "C" => "sample3",
               },
               {
               "A" => "sample1",
               "B" => "sample2",
               "C" => "sample3",
               }
            ]
        }
}

数组中的所有条目都包含相同的数据。为什么?

4

1 回答 1

2

尝试通过每个循环创建一个新的模板数组。我认为您不能在将密钥用作密钥时更改密钥的值。

@cdr.each do |cdr|
    temp_inst = template.clone
    temp_inst["A"] = cdr.start
    temp_inst["B"] = cdr.end
    temp_inst["C"] = cdr.clid
    skeleton["timeline"]["data"] << temp_inst
end
于 2012-04-15T23:06:37.763 回答