Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the "sort" and "sort!" method in ruby? [duplicate]

From Ruby's official documentation:

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.

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.

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

The result seems the same, so what's the difference?

like image 646
Fabio Avatar asked Jul 17 '26 13:07

Fabio


1 Answers

sort will not modify the original array whereas sort! will
('!' is the bang method in ruby, it will replace the existing value)
For example:

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

where as

a = [4,3,2,5,1]
a.sort! # => [1,2,3,4,5]
a is now [1,2,3,4,5]
like image 172
Amit Thawait Avatar answered Jul 19 '26 01:07

Amit Thawait