我想按字母對字串陣列進行排序,但將一個強制放在陣列的前面
p ['Home', 'Contact', 'Profile', 'Jobs', 'Privacy'].sort { |x, y|
if x == 'Privacy'
-1
else
x <=> y
end
}
給我 [“聯系方式”、“家庭”、“作業”、“隱私”、“個人資料”]
而不是 [“隱私”、“聯系方式”、“家庭”、“作業”、“個人資料”]
最終我想按名稱屬性對一組物件進行排序
class Page
include Comparable
def <=> (other)
if self.name == 'Jobs'
-1
else
self.name <=> other.name
end
end
end
[Page.new('Contact'), Page.new('Home'), Page.new('Jobs')...].sort
但是在 Comparable 類中覆寫 <=> 效果不佳
uj5u.com熱心網友回復:
您只需要為x和指定排序y:
["Home", "Contact", "Profile", "Jobs", "Privacy"].sort { |x, y|
if x == "Privacy" # "Privacy" <=> y
-1 # y is lower
elsif y == "Privacy" # x <=> "Privacy"
1 # "Privacy" is higher
else # the rest
x <=> y # use default sort order
end
}
# => ["Privacy", "Contact", "Home", "Jobs", "Profile"]
使用時同樣的事情Comparable:
class Page
include Comparable
def initialize name
@name = name
end
def <=> other
if @name == "Privacy"
-1
elsif other == "Privacy"
1
else
@name <=> other
end
end
end
>> [Page.new("Contact"), Page.new("Home"), Page.new("Jobs"), Page.new("Privacy")].sort
=> [#<Page:0x00007f8688624d30 @name="Privacy">, #<Page:0x00007f8688624ec0 @name="Contact">, #<Page:0x00007f8688624e20 @name="Home">, #<Page:0x00007f8688624da8 @name="Jobs">]
我知道的另一種方式:
>> ["Home", "Contact", "Profile", "Jobs", "Privacy"]
.partition{|i| i == "Privacy"}
.flat_map(&:sort)
=> ["Privacy", "Contact", "Home", "Jobs", "Profile"]
好的,我只是想知道:
require "benchmark"
a = (1..100_000).map{ rand(36**8).to_s(36) } ["privacy"]
d = a.dup # because `.delete` modifies the array
Benchmark.bm(15) do |b|
b.report("Delete Sort") { [d.delete("privacy"), *d.sort] }
b.report("Partition Sort") { a.partition{|i| i == "privacy"}.flat_map(&:sort) }
b.report("Sort by String") { a.sort_by {|i| i == "privacy" ? "" : i } }
b.report("Sort") { a.sort {|x, y| if x == "privacy";-1; elsif y == "privacy";1; else x<=>y end } }
b.report("Sort by Array") { a.sort_by {|s| s == "privacy" ? [0, ""] : [1, s] } }
end
user system total real
Delete Sort 0.035848 0.000000 0.035848 ( 0.035891)
Partition Sort 0.045608 0.000044 0.045652 ( 0.045711)
Sort by String 0.068656 0.000018 0.068674 ( 0.068733)
Sort 0.307052 0.000000 0.307052 ( 0.307237)
Sort by Array 0.493351 0.000000 0.493351 ( 0.493606) # making arrays is expensive
uj5u.com熱心網友回復:
試試下面的。
arr = ['Home', 'Contact', 'Profile', 'Jobs', 'Privacy']
arr.sort_by { |s| s == 'Privacy' ? [0, ''] : [1, s] }
#=> ["Privacy", "Contact", "Home", "Jobs", "Profile"].
Enumerable#sort_by使用Array#<=>對陣列進行排序。尤其參見后一個檔案的第三段。
請注意,第二個元素[0, '']是任意的。那是因為它從未被sort_by. 例如,[0, { a:1, b:2 }]或者[0]也可以。
它可能比使用sort_by更快sort只為陣列的sort_by每個元素計算一次雙元素陣列,而sort對于它考慮的每個成對排序執行兩次可比較的計算相比,使用起來更快。
更好的是,在@Alex 的評論中建議:
arr.sort_by { |s| s == "Privacy" ? "" : s }
或者,您可以撰寫:
a = arr.sort
[a.delete('Privacy'), *a]
#=> ["Privacy", "Contact", "Home", "Jobs", "Profile"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507561.html
標籤:红宝石
下一篇:Watir-抓取專案網格
