ruby alphanumeric sort not working as expected

前端 未结 4 944
盖世英雄少女心
盖世英雄少女心 2021-01-25 04:04

Given the following array:

y = %w[A1 A2 B5 B12 A6 A8 B10 B3 B4 B8]
=> [\"A1\", \"A2\", \"B5\", \"B12\", \"A6\", \"A8\", \"B10\", \"B3\", \"B4\", \"B8\"]
         


        
4条回答
  •  一个人的身影
    2021-01-25 04:46

    If you know what the maximum amount of digits in your numbers is you can also prefix your numbers with 0 during comparison.

    y.sort_by { |string| string.gsub(/\d+/) { |digits| format('%02d', digits.to_i) } }
    #=> ["A1", "A2", "A6", "A8", "B3", "B4", "B5", "B8", "B10", "B12"]
    

    Here '%02d' specifies the following, the % denotes the formatting of a value, the 0 then specifies to prefix the number with 0s, the 2 specifies the total length of the number, the d specifies that you want the output in decimals (base 10). You can find additional info here.

    This means that 'A1' will be converted to 'A01', 'B8' will become 'B08' and 'B12' will stay 'B12', since it already has 2 digits. This is only used during comparison.

提交回复
热议问题