Sort an Array of Strings by their Integer Values

后端 未结 8 1902
無奈伤痛
無奈伤痛 2021-02-04 00:54

Let\'s say I have an unsorted array from 1 to 10, as shown below...

a = ["3", "5", "8", "4", "1", "2",         


        
8条回答
  •  梦如初夏
    2021-02-04 01:07

    If you convert all strings to integers beforehand, it should work as expected:

    a.map(&:to_i).sort
    => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    

提交回复
热议问题