3

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?

Fabio
  • 2,074
  • 2
  • 24
  • 38
  • `sort` **Returns a new array created by sorting self** while `sort!` **Sorts self in place**, it is written in the documentation you posted... – toro2k Oct 31 '13 at 09:33
  • Yes, Neil it's a possible duplication of that question. I wasn't aware of that though because i'm new to Ruby. Sorry. Let's say I'm innocient this time :) – Fabio Oct 31 '13 at 09:37
  • That's an automated message from the close vote. No problem at all, the majority of closed questions are asked in good faith. But the correct result for SO is that this question should be closed, unless perhaps it catches everyone's imagination due to wording of question and answers then gets enough votes that it becomes the *new* best version of the question. – Neil Slater Oct 31 '13 at 09:50
  • Yes i agree. Thanks for your contribution to SO. – Fabio Oct 31 '13 at 10:02

3 Answers3

14

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]
oz123
  • 27,559
  • 27
  • 125
  • 187
Amit Thawait
  • 4,862
  • 2
  • 31
  • 25
0

In rails ! used to apply changes and update its calling object means

a.sort will only return sorted array but a.sort! will return sorted array and also save new sort result in a variable.

Ahmad Hussain
  • 2,443
  • 20
  • 27
0
'!' 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.
thiyaram
  • 242
  • 2
  • 8