题
所以我有以下的散列/数组:
{"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)
不隶属于 StackOverflow