组合2个字符串数组以在Ruby中创建哈希数组

时间:2017-06-05 21:33:02

标签: arrays ruby

我有以下数据:

fields = ["player_id", "name", "team", "player_id", "name", "team", "player_id", "name", "team"]
values = ["001", "Pound", "Monstars", "002", "Bang", "Monstars", "003", "Jordan", "Looney Tunes"]

我想创建一个哈希数组,因此数据将如下所示:

[{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]

在我寻求改进的过程中,我认为我还在做更多必要的步骤:

sliced_fields = fields.each_slice(3).to_a
=> [["player_id", "name", "team"], ["player_id", "name", "team"], ["player_id", "name", "team"]]

sliced_values = values.each_slice(3).to_a
=> [["001", "Pound", "Monstars"], ["002", "Bang", "Monstars"], ["003", "Jordan", "Looney Tunes"]]

new_array = sliced_values.map { |i| Hash[sliced_fields[sliced_values.index(i)].zip(i)] }
=> [{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]

有没有更简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

你非常接近。先zip,然后each_slice

fields.zip(values).each_slice(3).map(&:to_h)

在repl.it上查看:https://repl.it/I7S3