How to sort an alphanumeric array in ruby

后端 未结 8 1809
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 16:01

How I can sort array data alphanumerically in ruby?

Suppose my array is a = [test_0_1, test_0_2, test_0_3, test_0_4, test_0_5, test_0_6, test_0_7, test_0_8, te

8条回答
  •  盖世英雄少女心
    2021-01-19 16:40

    A generic algorithm for sorting strings that contain non-padded sequence numbers at arbitrary positions.

    padding = 4
    list.sort{|a,b|
      a,b = [a,b].map{|s| s.gsub(/\d+/){|m| "0"*(padding - m.size) + m } }
      a<=>b
    }
    

    where padding is the field length you want the numbers to have during comparison. Any number found in a string will be zero padded before comparison if it consists of less than "padding" number of digits, which yields the expected sorting order.

    To yield the result asked for by the user682932, simply add .reverse after the sort block, which will flip the natural ordering (ascending) into a descending order.

    With a pre-loop over the strings you can of course dynamically find the maximum number of digits in the list of strings, which you can use instead of hard-coding some arbitrary padding length, but that would require more processing (slower) and a bit more code. E.g.

    padding = list.reduce(0){|max,s| 
      x = s.scan(/\d+/).map{|m|m.size}.max
      (x||0) > max ? x : max
    }
    

提交回复
热议问题