Sorting an array of arrays in Ruby

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

    sort_by

    Instead of using spaceship operator (<=>) give a try to sort_by

    device_array.sort_by { |el| el[4] }
    

    Though if you know that the forth element is the last one, you can use el.last too in the block.

    Ruby docs: Enumerable#sort_by

提交回复
热议问题