从你的问题很难说出你想要什么。特别是因为您要求的顺序与正常排序创建的顺序完全相同。
无论如何,这是一种按照您想要的方式创建“自定义排序”顺序的方法。这与常规排序之间的区别在于,在这种排序中,可以使某些类型的字符或字符集胜过其他类型。
array = [
{color: '5 absolute'},
{color: '5.0'},
{color: '50 hello'},
{color: 'edge'}
]
p array.sort_by{|x| x[:color]} #=> [{:color=>"5 absolute"}, {:color=>"5.0"}, {:color=>"50 hello"}, {:color=>"edge"}]
# '50 hello' is after '5.0' as . is smaller than 0.
解决这个问题有点棘手,我会这样做:
# Create a custom sort order using regexp:
# [spaces, dots, digits, words, line_endings]
order = [/\s+/,/\./,/\d+/,/\w+/,/$/]
# Create a union to use in a scan:
regex_union = Regexp.union(*order)
# Create a function that maps the capture in the scan to the index in the custom sort order:
custom_sort_order = ->x{
x[:color].scan(regex_union).map{|x| [order.index{|y|x=~y}, x]}.transpose
}
#Sort:
p array.sort_by{|x| custom_sort_order[x]}
# => [{:color=>"5 absolute"}, {:color=>"50 hello"}, {:color=>"5.0"}, {:color=>"edge"}]