문제

So I have the following hashes/arrays:

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

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

That first hash has an array for number while the second one doesn't.

It's wreaking havoc trying to loop through the data (specifically when there's only one tracking/notes combo).

Ultimately I'm wanting to be able to do an each loop on each tracking/notes combo.

도움이 되었습니까?

해결책

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"}]

Now, each will be an array of hashes and you can use each to iterate through them.

다른 팁

Something like this?

hash["number"] = [ hash["number"] ] unless hash["number"].kind_of?(Array)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top