如何循环检查并在哈希内迭代以创建/填充键值对?

时间:2018-05-24 10:08:19

标签: ruby-on-rails ruby

我有类似

的东西
strands = Strand.all


data = {}
data["data"] = {
              strands.each do |strand|
                "#{strand.name}" = {"description" => "#{strand.description}",
                                     if strand.standards.present?
                                        "children" => 
                                        strand.standards.each do |standard|
                                            {"#{standard.name}" => {"description" => "#{standard.description}"}
                                          }
                                        end
                                      end
                                    } 
              end
}

所以我需要生成一个像下面那样的json结构

"data": {
     "testStrand3Code": {
            "description" : " some descr.. .",
            "children" : {"standard3Code" : {
                "description" : " some descr.. ."
            }}
      }
}

我无法迭代strands.each do |strand|并且它给我一个错误。我想我不能在哈希{}中运行逻辑代码?我该怎么做?谢谢。

1 个答案:

答案 0 :(得分:2)

(data = {})["data"] =
  strands.map do |strand|
    [strand.name, 
      {
        "description" => strand.description,
        "children" => strand.standards.map do |standard|
          [standard.name, {"description" => standard.description}]
        end.to_h
      }
    ]
  end.to_h