How to sort an alphanumeric array in ruby

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

    If you simply sort as string, you will not get the correct ordering between 'test_2' and 'test_10', for example. So do:

    sort_by{|s| s.scan(/\d+/).map{|s| s.to_i}}.reverse
    

提交回复
热议问题