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.

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里,能看到很多加了感叹号的函数,都意味着对函数操作的对象进行了状态更改。

转载于:https://www.cnblogs.com/dami520/p/3222674.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值