如何创建包含动态构建的哈希数组的哈希

时间:2011-07-07 15:50:09

标签: ruby arrays hash

我需要创建这样的东西:

"paxReference" => [{
  "ptc" => "ADT",                 
  "traveller" => [
    {
      "ref" => "1"               
    },
    { 
      "ref" => "2"
    }
  ]
},
{
  "ptc" => "CH",                 
  "traveller" => [
    {
      "ref" => "3",                 
    },
    {
      "ref" => "4",                
    }
  ]
},
]

但哈希“旅行者”的数组必须动态构建,我的意思是,如果参数ADT_number为4,我必须包括4

"ref" => "1"
"ref" => "2"
"ref" => "3"
"ref" => "4"

“CH”段也是如此。

我如何在Ruby中执行此操作?

输出应该如下所示:

<paxReference>
 <ptc>ADT</ptc>
 <traveller>
  <ref>1</ref>
 </traveller>
 <traveller>
  <ref>2</ref>
 </traveller>
</paxReference>
<paxReference>
 <ptc>CH</ptc>
 <traveller>
  <ref>3</ref>
 </traveller>
 <traveller>
  <ref>4</ref>
 </traveller>
</paxReference>

1 个答案:

答案 0 :(得分:0)

paxReference = ptcs.map do |ptc|
  out_hash = {}
  out_hash["ptc"] = ptc
  out_hash["traveler"] = ADT_number.times.map {|i| {"ref" => i }}
end

这是在ptcs是一个数组的情况下,并且每个ADT_number都不会改变。如果ADT_number发生了变化,那么你会想要获取带索引或类似内容的东西。