简体   繁体   中英

Ruby: How can I make these objects the same?

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.

像这样吗

hash["number"] = [ hash["number"] ] unless hash["number"].kind_of?(Array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM