本文簡要介紹ruby語言中 Array.sort!
的用法。
用法
sort! → self
sort! {|a, b| ... } → self
返回 self
,其元素已就地排序。
在沒有塊的情況下,使用運算符 <=>
比較元素(參見 Comparable
):
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a.sort!
a # => ["a", "b", "c", "d", "e"]
使用塊,調用具有每個元素對的塊;對於每個元素對 a
和 b
,塊應返回一個整數:
-
當
b
跟隨a
時為負數。 -
當
a
和b
相等時為零。 -
當
a
跟隨b
時為正。
例子:
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a.sort! {|a, b| a <=> b }
a # => ["a", "b", "c", "d", "e"]
a.sort! {|a, b| b <=> a }
a # => ["e", "d", "c", "b", "a"]
當塊返回零時,a
和 b
的順序是不確定的,並且可能不穩定:
a = 'abcde'.split('').shuffle
a # => ["e", "b", "d", "a", "c"]
a.sort! {|a, b| 0 }
a # => ["d", "e", "c", "a", "b"]
相關用法
- Ruby Array.sort用法及代碼示例
- Ruby Array.sort_by用法及代碼示例
- Ruby Array.sort_by!用法及代碼示例
- Ruby Array.slice!用法及代碼示例
- Ruby Array.shuffle!用法及代碼示例
- Ruby Array.sample()用法及代碼示例
- Ruby Array.select!用法及代碼示例
- Ruby Array.slice()用法及代碼示例
- Ruby Array.sum用法及代碼示例
- Ruby Array.shift用法及代碼示例
- Ruby Array.sample用法及代碼示例
- Ruby Array.slice用法及代碼示例
- Ruby Array.shuffle用法及代碼示例
- Ruby Array.select用法及代碼示例
- Ruby Array.push用法及代碼示例
- Ruby Array.hash用法及代碼示例
- Ruby Array.to_a用法及代碼示例
- Ruby Array.to_h用法及代碼示例
- Ruby Array.to_s用法及代碼示例
- Ruby Array.array + other_array用法及代碼示例
- Ruby Array.take()用法及代碼示例
- Ruby Array.reject!用法及代碼示例
- Ruby Array.flatten!用法及代碼示例
- Ruby Array.reject用法及代碼示例
- Ruby Array.repeated_permutation()用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Array.sort!。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。