Syn*_*ter 1 ruby arrays dictionary
我是 Ruby 新手,并在此链接上尝试了几个示例。
说,我有两个数组
Array1: ["square", "circle", "triagle"]
Array2: ["red", "blue"]
Run Code Online (Sandbox Code Playgroud)
我想创建一个地图,例如,
[{:shape=>"square", :color=>"red"}]
[{:shape=>"square", :color=>"blue"}]
[{:shape=>"circle", :color=>"red"}]
[{:shape=>"circle", :color=>"blue"}]
[{:shape=>"triangle", :color=>"red"}]
[{:shape=>"triangle", :color=>"blue"}]
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的代码。
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)
Run Code Online (Sandbox Code Playgroud)
上述代码的输出:
[{:shape=>["square", "circle", "triangle"], :color=>"abc"}]
Run Code Online (Sandbox Code Playgroud)
我不太确定如何遍历array2。
我来自 Java 背景,仍然试图了解如何从函数返回整个地图以及如何处理数组的每个元素并创建地图。
如果您需要的是一个散列数组,其中每个散列都有键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"}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |