ruby 數組array 排序sort 和sort!

1.
sort → new_ary click to toggle source
sort { |a, b| block } → new_ary

Returns a new array created by sorting self.html

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.ruby

See also Enumerable#sort_by.ide

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.ui

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.spa

See also Enumerable#sort_by.code

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-sort3.sort和sort!的區別:sort和sort!函數,默認都使用 <=>比較,他們的區別在於:sort! 可能會改變原先的數組,因此加個感嘆號提醒sort 返回的是新數組,沒對原先的數組進行修改在ruby的SDK裏,能看到不少加了感嘆號的函數,都意味着對函數操做的對象進行了狀態更改。
相關文章
相關標籤/搜索