Is there a natural_sort_by method for Ruby?

前端 未结 7 1148
说谎
说谎 2020-12-06 05:06

I have a list of files with a bunch of attributes. One of the attributes is the file name which is how I would like to sort the list. However, the list goes something like t

7条回答
  •  北海茫月
    2020-12-06 05:43

    array.sort_by{|x| ( x.class == Array ? x.join(" ") : x.to_s ).split(/(\d+)/).map{|x| x.to_s.strip }.select{|x| x.to_s != "" }.map{|x| x =~ /\d+/ ? x.to_s.rjust(30) : x }}
    

    This can compare arrays by arrays in the sort_by method even if the type of the matching items differ. Even if there are deeper nested arrays. Example:

    [ "3  a   22", "b  22     1", "   b  5  ", [11, 2, [4, 5]] ] #=>
    [ "3  a   22", [11, 2, [4, 5]], "   b  5  ", "b  22     1" ]
    

    The point here is that during the sort if an item is a nested array then we convert it to a string beforehand. And if parts of the string contain digits only then we do not convert them to numeric values but instead extend them with spaces, like:

    30 #=> "                         30"
    

    This way all objects will be compatible strings and the sorting will be able to compare them resulting in a numeric sort if the matching objects at their positions are numbers only.

提交回复
热议问题