排序动态多维数组

时间:2015-09-03 08:42:10

标签: arrays ruby sorting multidimensional-array

我试着用第一个值在Ruby中对二维数组进行排序,如下所示:

files_array = Array.new(2) {Array.new}

files_array[0][0] = 42
files_array[1][0] = "/media/js/aefc015sdfsdf0728175535.js42"
files_array[0][1] = 21
files_array[1][1] = "/media/js/aefc015sdfsdf0728175535.js21"
files_array[0][2] = 30
files_array[1][2] = "/media/js/aefc015sdfsdf0728175535.js30"

我试过

files_array.sort!{|a,b| b[0] <=> a[0]} 

但它返回:

`sort!': comparison of Array with Array failed (ArgumentError)

这就是我想要对数组进行排序的方式:

files_array[0][0] = 21
files_array[1][0] = "/media/js/aefc015sdfsdf0728175535.js21"
files_array[0][1] = 30
files_array[1][1] = "/media/js/aefc015sdfsdf0728175535.js30"
files_array[0][2] = 42
files_array[1][2] = "/media/js/aefc015sdfsdf0728175535.js42"

2 个答案:

答案 0 :(得分:0)

`sort!': comparison of Array with Array failed (ArgumentError)

这是因为a[0]b[0]是数组数组的元素,即它们本身就是数组。

如果你这样做了:

files_array.sort!{|a,b| b[0][0] <=> a[0][0]} 

它会起作用。

顺便说一句,这看起来像关联数组比数组数组更好的一个很好的例子。

files_hash = {
  42 => "/media/js/aefc015sdfsdf0728175535.js42",
  21 => "/media/js/aefc015sdfsdf0728175535.js21",
  30 => "/media/js/aefc015sdfsdf0728175535.js30"
}

不仅代码中的内容更清晰,而且您不需要维护已排序的二维数组。

答案 1 :(得分:0)

试试这个会对你有用:

files_array =   [[42,"/media/js/aefc015sdfsdf0728175535.js42"],[21,"/media/js/aefc015sdfsdf0728175535.js21"],[30,"/media/js/aefc015sdfsdf0728175535.js30"]]

    sorted = files_array.sort { |x,y| x[0] <=> y[0] }

 puts   sorted

结果:

21
/media/js/aefc015sdfsdf0728175535.js21
30
/media/js/aefc015sdfsdf0728175535.js30
42
/media/js/aefc015sdfsdf0728175535.js42