Sort an Array of Strings by their Integer Values

后端 未结 8 1895
無奈伤痛
無奈伤痛 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]
    
    0 讨论(0)
  • 2021-02-04 01:12

    The cheap way would be to zero fill on the left and make all numbers 2 digit.

    0 讨论(0)
  • 2021-02-04 01:18

    I'll throw another method out there since it's the shortest way I can think of

    a.sort_by(&:to_i)
    
    0 讨论(0)
  • 2021-02-04 01:22

    Another option, that can be used in your example or others arrays like

    a = ["teste", "test", "teste2", "tes3te", "10teste"]
    

    is:

    a.sort_by! {|s| s[/\d+/].to_i}
    
    0 讨论(0)
  • 2021-02-04 01:24
    a.sort { |a,b| a.to_i <=> b.to_i }
    
    0 讨论(0)
  • 2021-02-04 01:29

    The reason for this behavior is that you have an array of strings and the sort that is being applied is string-based. To get the proper, numeric, sorting you have to convert the strings to numbers or just keep them as numbers in the first place. Is there a reason that your array is being populate with strings like this:

    a = ["3", "5", "8", "4", "1", "2", "9", "10", "7", "6"]
    

    Rather than numbers like this:

    a = [3, 5, 8, 4, 1, 2, 9, 1, 7, 6]
    

    ?

    0 讨论(0)
提交回复
热议问题