How to sort an alphanumeric array in ruby

后端 未结 8 1815
没有蜡笔的小新
没有蜡笔的小新 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:24

    Similar to @ctcherry answer, but faster:

    a.sort_by {|s| "%s%05i%05i" % s.split('_') }.reverse
    

    EDIT: My tests:

    require 'benchmark'
    ary = []
    100_000.times { ary << "test_#{rand(1000)}_#{rand(1000)}" }
    ary.uniq!; puts "Size: #{ary.size}"
    
    Benchmark.bm(5) do |x|
      x.report("sort1") do
        ary.sort_by {|e| "%s%05i%05i" % e.split('_') }.reverse
      end
      x.report("sort2") do
        ary.sort { |a,b|
          ap = a.split('_')
          a = ap[0] + "%05d" % ap[1] + "%05d" % ap[2]
          bp = b.split('_')
          b = bp[0] + "%05d" % bp[1] + "%05d" % bp[2]
          b <=> a
        } 
      end
      x.report("sort3") do
        ary.sort_by { |v| a, b, c = v.split(/_+/); [a, b.to_i, c.to_i] }.reverse
      end
    end
    

    Output:

    Size: 95166
    
               user     system      total        real
    sort1  3.401000   0.000000   3.401000 (  3.394194)
    sort2 94.880000   0.624000  95.504000 ( 95.722475)
    sort3  3.494000   0.000000   3.494000 (  3.501201)
    

提交回复
热议问题