开发者

Ruby: How can I make these objects the same?

So I have the following hashes/arrays:

{"number"=>[{"tracking"=>"1Z81E开发者_运维知识库74W0393736553", "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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜