ruby中“sort”和“sort!”方法有什么区别?

What is the difference between the “sort” and “sort!” method in ruby?

本问题已经有最佳答案,请猛点这里访问。

来自Ruby的官方文档:

sort → new_ary 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.

1
2
3
a = ["d","a","e","c","b" ]
a.sort                    #=> ["a","b","c","d","e"]
a.sort { |x,y| y <=> x }  #=> ["e","d","c","b","a"]

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.

1
2
3
a = ["d","a","e","c","b" ]
a.sort!                    #=> ["a","b","c","d","e"]
a.sort! { |x,y| y <=> x }  #=> ["e","d","c","b","a"]

结果似乎是一样的,那么有什么区别呢?


sort将不修改原始数组,而sort!将修改原始数组。("!"是ruby中的bang方法,它将替换现有值)例如:

1
2
3
a = [4,3,2,5,1]
a.sort # => [1,2,3,4,5]
a is still [4,3,2,5,1]

在哪里

1
2
3
a = [4,3,2,5,1]
a.sort! # => [1,2,3,4,5]
a is now [1,2,3,4,5]

1
2
3
4
5
'!' is the bang method in ruby, it will replace the existing value


ex: .sort is a normal sorting method in ruby
    .sort! its a bang method in ruby its override the existing value.


在铁轨上!用于应用更改并更新其调用对象意味着

a.sort只返回排序后的数组,而返回a.sort!将返回已排序的数组,并将新的排序结果保存到变量中。