简体   繁体   English

迭代数组的哈希

[英]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. 我已经尝试过使用“ each_with_index”,键,值散列方式的许多可能解决方案,但是没有运气。
Thanks in advance. 提前致谢。

Assuming every value in Hash is an Array of same length, transpose array hash.values : 假设Hash中的每个值都是相同长度的Array,请transpose数组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. 虽然transpose解决方案非常好,但是当并非所有值数组都具有相同数量的元素时,它将出错。 This will still work (replacing missing elements with nil ): 这仍然可以工作(用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. 如果您知道输入格式正确,请使用transpose选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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