简体   繁体   中英

Iterate hash of arrays

{"title"=>["111", "222", "333"], "rating"=>["1", "2", "3"], "reviews"=>["11", "22", "33"]}


I have data with me from the form in the above format.

Now I want to iterate through this loop so that I can get data in below sequence as per my requirement:

["111", "1", "11"], ["222", "2", "22"], ["333", "3", "33"]

Actually I have to save each record in my database in the way so that a title, a rating and a review forms one row for my database table.
I have tried many possible solutions with 'each_with_index', key, value hash way, but no luck.
Thanks in advance.

Assuming every value in Hash is an Array of same length, transpose array hash.values :

hash = {"title"=>["111", "222", "333"], "rating"=>["1", "2", "3"], "reviews"=>["11", "22", "33"]}
hash.values
#=> [["111", "222", "333"], ["1", "2", "3"], ["11", "22", "33"]]
hash.values.transpose
#=> [["111", "1", "11"], ["222", "2", "22"], ["333", "3", "33"]]

While the transpose solution is very nice, it will error out when not all value arrays have the same number of elements. This will still work (replacing missing elements with nil ):

h.values.reduce(:zip).map(&:flatten)
#=> [["111", "1", "11"], ["222", "2", "22"], ["333", "3", "33"]]

If you know that your input is well-formed, go for the transpose option.

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