所以我有以下的散列/数组:

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

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

这第一散列具有用于number阵列而第二个没有。

它肆虐通过数据(具体地,当只有一个跟踪/笔记组合)。

试图环

最后,我希望能够做到每个跟踪/音符组合的each循环。

有帮助吗?

解决方案

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通过它们进行迭代。

其他提示

像这样?

hash["number"] = [ hash["number"] ] unless hash["number"].kind_of?(Array)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top