arrays - Ruby 中的有序数组连接

标签 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 开始的元素没有写入正确的 block 。

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

最佳答案

试试这个

[*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"
]

关于arrays - Ruby 中的有序数组连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032910/

相关文章:

ios - 自定义单元格图像作为 Swift 中的附件类型

java - 在Java中查找2个数组中匹配元素的数量

ruby - 设置 RubyMine2 以运行和调试 Sinatra 应用程序

ruby-on-rails - 我如何在 rails 中使外键/主键不区分大小写

android - 使用retrofit2.0解析JSON对象

android - JSON 解析器性能低下

javascript - 在 JS 中过滤具有深层嵌套数组的数组

c - 通过同时使用 "Element-by-Element"和 "Designated"技术初始化数组时出现意外输出

c - 将表指针从 C 传递到汇编函数

ruby - 通过命令行添加文件到redmine