arrays - 如何遍历两个数组并在 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 背景,仍然试图了解如何从函数返回整个映射以及如何处理数组的每个元素并创建映射。
解决方案
如果您需要的是一个哈希数组,其中每个哈希都有键shape
and 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"}]
推荐阅读
- rust - 为什么循环内的一些 while-let 分配无法编译,“不能一次多次借用可变”?
- java - 无法从文件中读取地图
- c# - 为什么这段代码会删掉文本的最后一行?
- python - 与输入维度相关的多输入 Keras 模型出现错误
- python - 我的代码正在返回重复的行,而不是像在 sqlite 中那样
- java - Android 如何从 Main Activity 中的另一个类调用 Activity 数据类型?
- node.js - 处理大量请求而不会崩溃
- macos - 如何像使用 bash 一样在 zsh 中使用参数打开 macOS 程序?
- reactjs - REACTJS 修改 CSV 中的列数据
- python - 如何将模块中的所有类作为列表导入?