Sort an Array of Strings by their Integer Values

后端 未结 8 1896
無奈伤痛
無奈伤痛 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:30

    For the special case (e-commerce price list) you mentioned

    a = ["0-10", "11-20", "21-30", "31-40"]
    

    let's add a few more values to this array (as it was mentioned as price list). so

    a = ["0-10", "11-20", "120-150", "110-120", "21-30", "31-40"]
    

    we can sort such an array using the following

    a.sort.sort_by(&:length)
    
    0 讨论(0)
  • 2021-02-04 01:31

    As your updated question states:

    array.sort_by {|elt| ary = elt.split("-").map(&:to_i); ary[0] + ary[1]}
    

    even geekier:

    array.sort_by {|elt| ary = elt.split("-").map(&:to_i).inject(&:+)}
    
    0 讨论(0)
提交回复
热议问题