数组排序的Ruby中的数组 [英] Sorting an array of arrays in Ruby
问题描述
我有数组像这样的数组:
I have an array of arrays like so:
irb(main):028:0> device_array
=> [["name1", "type1", ["A", "N", "N"], ["Attribute", "device_attribute"], 9], ["name2","type2", ["A", "N", "N"], ["Attribute", "device_attribute"], 7]]
我想,第4单元对整个device_array排序。
I would like to sort the entire device_array on the 4th element.
我试过
AllDevicesController.all_devices.sort do | a,b |
for i in 0..(AllDevicesController.all_devices.length - 1) do
a[i][4] <=> b[i][4]
end
end
我也试过:
AllDevicesController.all_devices.sort do | a,b |
a[][4] <=> b[][4]
end
这两种方法都没有奏效。
Both methods have not worked.
我是用这个作为参考:
<一href=\"http://ariejan.net/2007/01/28/ruby-sort-an-array-of-objects-by-an-attribute/\">http://ariejan.net/2007/01/28/ruby-sort-an-array-of-objects-by-an-attribute/
我想我失去了一些东西rubyish使这很容易。
I imagine I'm missing something rubyish that makes this really easy.
推荐答案
您不能使用&LT; =&GT;
与无
。
您code应该是这样的:
Your code should be something like this:
AllDevicesController.all_devices.sort do |a, b|
a[4].nil? ? -1 : b[4].nil? ? 1 : a[4] <=> b[4]
end
这将使子阵,在结果的开始没有索引4的元素。要做到这一点的其他方式,交换 1
与 1
。
This will put the sub-arrays that have no element of index 4 at the beginning of the result. To do it the other way around, swap -1
with 1
.
您也可以使用 sort_by
而不是排序
。我觉得这已经用Ruby 1.8.7(所以如果你使用的是旧版本,它可能无法正常工作)被引入。它会是这样的:
You could also use sort_by
instead of sort
. I think this has been introduced in Ruby 1.8.7 (so it might not work if you are using an older version). It goes something like:
AllDevicesController.all_devices.sort_by { |e| e.nil? ? 0 : e[4] }
这会把子阵,无4元,如果它是0更改此常量适合你。
This will treat sub-arrays with no 4th element as if it was 0. Change this constant to suit you.
编辑:
在你调整的投入,现在很清楚你是非常接近正确的答案。您code应该是:
After you adjusted the input, it is now clear you were very close to the right answer. Your code should have been:
AllDevicesController.all_devices.sort do |a, b|
a[4] <=> b[4]
end
或简单的(假设的Ruby 1.8.7或以上):
Or simple (assuming Ruby 1.8.7 or more):
AllDevicesController.all_devices.sort_by { |e| e[4] }
在这两种情况下,变量 A
和 B
将包含原始数组中的元素,这就是为什么你可以直接在任意位置访问一个元素(你不需要像 A [] [4]
,这是不正确的Ruby语法)。
In both cases, the variables a
and b
will contain elements of the original array, this is why you can directly access an element in any position (and you don't need something like a[][4]
, which is incorrect Ruby syntax).
这篇关于数组排序的Ruby中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!