首页 > 解决方案 > 如何遍历两个数组并在 Ruby 中创建地图

问题描述

我是 Ruby 新手,在这个链接上尝试了几个例子。

说,我有两个数组

Array1: ["square", "circle", "triagle"]

Array2: ["red", "blue"]

我想创建一个地图,例如,

[{:shape=>"square", :color=>"red"}]
[{:shape=>"square", :color=>"blue"}]
[{:shape=>"circle", :color=>"red"}]
[{:shape=>"circle", :color=>"blue"}]
[{:shape=>"triangle", :color=>"red"}]
[{:shape=>"triangle", :color=>"blue"}]

这是我尝试过的代码。

def processArray6(array1, array2)
    newMap = [array1].map do |entry|
    {
        shape: entry,
        color: "abc" # Should write another for-loop here to loop over array2
    }
    end
end

array1 = ["square", "circle", "triangle"]
array2 = ["red", "blue,"]

p processArray6(array1, array2)

上述代码的输出:

[{:shape=>["square", "circle", "triangle"], :color=>"abc"}]

我不太确定如何遍历array2。

我来自 Java 背景,仍然试图了解如何从函数返回整个映射以及如何处理数组的每个元素并创建映射。

标签: arraysrubydictionary

解决方案


如果您需要的是一个哈希数组,其中每个哈希都有键shapeand color,那么您可以product在 array1 和 array2 之间使用,然后只映射结果:

array1.product(array2).map { |shape, color| { shape: shape, color: color } }
# [{:shape=>"square", :color=>"red"}, {:shape=>"square", :color=>"blue"}, {:shape=>"circle", :color=>"red"}, {:shape=>"circle", :color=>"blue"}, {:shape=>"triagle", :color=>"red"}, {:shape=>"triagle", :color=>"blue"}]

推荐阅读