Sorting an array of arrays in Ruby

后端 未结 4 1928
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 00:07

I have an array of arrays like so:

irb(main):028:0> device_array
=> [[\"name1\", \"type1\", [\"A\", \"N\", \"N\"], [\"Attribute\", \"device_attribute\"], 9         


        
4条回答
  •  无人共我
    2021-02-07 00:21

    You can't use <=> with nil.

    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
    

    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.

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

    This will treat sub-arrays with no 4th element as if it was 0. Change this constant to suit you.

    EDIT:

    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
    

    Or simple (assuming Ruby 1.8.7 or more):

    AllDevicesController.all_devices.sort_by { |e| e[4] }
    

    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).

提交回复
热议问题