Sorting an array of arrays in Ruby

后端 未结 4 1922
佛祖请我去吃肉
佛祖请我去吃肉 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:25

    The 4th element is actually at index 3, which means you would do it like this:

    all_devices.sort do |a, b|
      a[3] <=> b[3]
    end
    

    If you really want to sort the elements at index 4 (which doesn't exist for the first element of all_devices), then you need to add comparison to the NilClass first:

    class NilClass
      def <=> (other)
        1
      end
    end
    
    all_devices.sort do |a, b|
      a[4] <=> b[4]
    end
    

    This will sort nil to the end. Change the return value of <=> to -1 to sort them to the front.

提交回复
热议问题