Ruby中的有序数组连接

时间:2017-10-31 10:20:01

标签: arrays ruby parsing hash

我有3个以下形式的数组:

arr1 = [11a,12b,13c,14d,15e,16f]
arr2 = [21g,22h,23i,24j,25k,26l]
arr3 = [31m,31n,32o,32p,33q,34r,35s,36t,36u]

您可以注意到元素编号中的第一个数字表示数组编号。第二个数字是数组中元素的标识符。

我需要以下列形式加入这些数组的元素:

11a
21g
31m
31n
12b
22h
32o
32p
13c
23i
33q
14d
24j
34r
15e
25k
35s
16f
26l
36t
36u

我正在尝试通过将数据连接到一个数组来组织数据。我是这样做的:

res_array=[]
last_element = res3.index(res3.last)
i=-1
loop do
i+=1
res_array<<arr1[i]
res_array<<arr2[i]
res_array<<arr3[i]
break if i >= last_element
end

我的决定很糟糕,因为我得到了错误的数据:

11a
21g
31m # wrong. lacking 31n
12b
22h
31n # is incorrect. here should be 32o and 32p
13c
23i
32o
14d
24j
32p # is incorrect. there should be 34r
15e
25k
33q # wrong. here should be 35s
16f
26l
34r # wrong. here should be 36t and 36u
35s
36t
36u

我的代码很糟糕,因为从3开始的元素没有写入正确的块。

我认为我需要创建一个额外的循环来执行res_array&lt;&lt; arr3 [i]用于序列号小于或等于前一个块的序列号的元素。

1 个答案:

答案 0 :(得分:3)

试试这个

[*arr1, *arr2, *arr3].sort_by { |item| [item[1], item[-1], item[0]]  }
[
    [ 0] "11a",
    [ 1] "21g",
    [ 2] "31m",
    [ 3] "31n",
    [ 4] "12b",
    [ 5] "22h",
    [ 6] "32o",
    [ 7] "32p",
    [ 8] "13c",
    [ 9] "23i",
    [10] "33q",
    [11] "14d",
    [12] "24j",
    [13] "34r",
    [14] "15e",
    [15] "25k",
    [16] "35s",
    [17] "16f",
    [18] "26l",
    [19] "36t",
    [20] "36u"
]