0

所以我有以下哈希/数组:

{"number"=>[{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}, {"tracking"=>"9102901001301227214058"}]}

{"number"=>{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}}

第一个哈希有一个数组,number而第二个没有。

试图循环遍历数据会造成严重破坏(特别是当只有一个跟踪/注释组合时)。

最终,我希望能够each对每个跟踪/注释组合进行循环。

4

2 回答 2

2
h1={"number"=>[{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}, {"tracking"=>"9102901001301227214058"}]}
h2={"number"=>{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}}
[h1["number"]].flatten
  => [{"notes"=>"Example note", "tracking"=>"1Z81E74W0393736553"}, {"tracking"=>"9102901001301227214058"}]
[h2["number"]].flatten
  => [{"notes"=>"Example note", "tracking"=>"1Z81E74W0393736553"}]

现在,每个都将是一个哈希数组,您可以使用它each来遍历它们。

于 2010-03-19T19:10:59.033 回答
1

像这样的东西?

hash["number"] = [ hash["number"] ] unless hash["number"].kind_of?(Array)
于 2010-03-19T19:06:33.983 回答