[英]array of hashes sort by
我有很多哈希值:
array = [
{color: '5 absolute', ... },
{color: '5.0', ... },
{color: '5.1', ... },
{color: 'last', ... },
{color: '50', ... },
{color: '5 elite', ... },
{color: 'edge'}
]
我需要訂購顏色:
5 absolute
5 elite
5.0
5.1
50
edge
last
優先級是:
first going spaces ' ',
then dots '.',
then digits '7',
then other 'string'
這就像SQL activerecord模擬查詢一樣 ,但是我不希望在后台進行這種困難的查詢。 我想要這個邏輯 。 如何使用AR查詢做到這一點?
您總是可以對哈希數組進行排序。
array.map{|h| h[:color]}.sort
=> ["5 absolute", "5 elite", "5.0", "5.1", "50", "edge", "last"]
以下內容首先按數字排序,然后按數字后面的字符串排序。
array = [{color: '5 absolute'}, {color: '5.0'}, {color: '5.1'},
{color: 'last'}, {color: '50'}, {color: '5 elite'},
{color: 'edge'}, {color: '6 absolute'}, {color: '7'}]
array.map{|h| h[:color]}.sort_by do |s|
n = s.to_f
if n == 0 && s.match(/\d/).nil?
n = Float::INFINITY
end
[n, s.split(" ")[-1]]
end
=> ["5.0", "5 absolute", "5 elite", "5.1", "6 absolute", "7", "50", "edge", "last"]
這樣嗎?
h = [{:color=>"5 absolute"},
{:color=>"5.0"},
{:color=>"5.1"},
{:color=>"last"},
{:color=>"50"},
{:color=>"5 elite"},
{:color=>"edge"}]
h.map(&:values).flatten.sort
# => ["5 absolute", "5 elite", "5.0", "5.1", "50", "edge", "last"]
或所有其他答案...
從您的問題很難說出您想要什么。 尤其是因為您要的訂單與通常的排序完全相同。
無論如何,這是一種按照您想要的方式創建“自定義排序”訂單的方法。 這種排序方式與常規排序方式的區別在於,這種排序方式可以使某些類型的字符或一組字符勝過其他類型。
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"}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.