gpt4 book ai didi

ruby - 在 Ruby 中将一个数组的值关联到另一个数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:23:08 25 4
gpt4 key购买 nike

在学习了一点 Ruby 之后,我正在构建一个简单的程序。我正在尝试将一个数组的值关联到另一个数组,这就是我目前所获得的结果。

ColorValues = ["Black", "Brown", "Red", "Orange", "Yellow", "Green", "Cyan", "Blue", "Violet", "Pink", "Grey"]  

(0..127).each_slice(12) {|i| p i}

.each_slice 返回这些数组

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

[24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

[36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]

[48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]

[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]

[72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83]

[84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95]

[96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107]

[108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119]

[120, 121, 122, 123, 124, 125, 126, 127]

然后我尝试做的是获取返回的数组并将它们与 ColorValues[] 数组中的每种颜色相关联

"Black" =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
"Brown" = [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

我确信有一种简单的方法可以做到这一点,我只是不确定如何着手去做。

最佳答案

使用 Enumerable#zipHash::[]

colorValues = ["Black", "Brown", "Red", "Orange", "Yellow", "Green", "Cyan", "Blue", "Violet", "Pink", "Grey"]  
Hash[colorValues.zip((0..127).each_slice(12))]
# => {"Black"=>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
# "Brown"=>[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
# "Red"=>[24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
# "Orange"=>[36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
# "Yellow"=>[48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
# "Green"=>[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71],
# "Cyan"=>[72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83],
# "Blue"=>[84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95],
# "Violet"=>[96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107],
# "Pink"=>[108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119],
# "Grey"=>[120, 121, 122, 123, 124, 125, 126, 127]}

关于ruby - 在 Ruby 中将一个数组的值关联到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21669130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com