在Ruby中将值从一个数组关联到另一个数组

时间:2014-02-10 04:32:14

标签: ruby

在学习了一点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]

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

3 个答案:

答案 0 :(得分:5)

使用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]}

答案 1 :(得分:1)

您可以使用zip:

ColorValues.zip( (0..127).each_slice(12) )

答案 2 :(得分:1)

方法#zip很方便,但事实证明你的问题在Ruby中非常频繁,我在#>>类上重载了Array运算符来执行压缩到哈希。首先,安装y_support gem。然后,

require 'y_support/core_ext/array' # or require 'y_support/all'
h = ColorValues >> ( 0..127 ).each_slice( 12 ) # returns a hash like in falsetru's answer
h["Black"] #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]