1.
sort → new_ary
click to toggle source
sort { |a, b| block } → new_ary
Returns a new array created by sorting self
.
Comparisons for the sort will be done using the <=>
operator or using an optional code block.
The block must implement a comparison between a
and b
, and return -1
, when a
follows b
, 0
when a
and b
are equivalent, or +1
if b
follows a
.
See also Enumerable#sort_by.
a = [ "d", "a", "e", "c", "b" ] a.sort #=> ["a", "b", "c", "d", "e"] a.sort { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
a.sort { |x,y| x <=> Y } #=> ["a", "b", "c", "d", "e"]
2.
sort! → ary
click to toggle source
sort! { |a, b| block } → ary
Sorts self
in place.
Comparisons for the sort will be done using the <=>
operator or using an optional code block.
The block must implement a comparison between a
and b
, and return -1
, when a
follows b
, 0
when a
and b
are equivalent, or +1
if b
follows a
.
See also Enumerable#sort_by.
a = [ "d", "a", "e", "c", "b" ] a.sort! #=> ["a", "b", "c", "d", "e"] a.sort! { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
參考鏈接:http://www.ruby-doc.org/core-2.0/Array.html#method-i-sort
3.sort和sort!的區別:
sort和sort!函數,默認都使用 <=>比較,他們的區別在於:
sort! 可能會改變原先的數組,所以加個感嘆號提醒
sort 返回的是新數組,沒對原先的數組進行修改
在ruby的SDK里,能看到很多加了感嘆號的函數,都意味着對函數操作的對象進行了狀態更改。