# Array#sort unexpected behaviour

**URL:** <https://www.ruby-forum.com/t/array-sort-unexpected-behaviour/128799>\
**Category:** Ruby\
**Created:** [February 11, 2008, 5:48pm UTC](https://www.ruby-forum.com/t/array-sort-unexpected-behaviour/128799 "2008-02-11T17:48:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![daniel\_SSSSkerud](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8e8cbc/32.png) [@daniel\_SSSSkerud](https://www.ruby-forum.com/u/daniel_SSSSkerud)\
**Post date:** [February 11, 2008, 5:48pm UTC](https://www.ruby-forum.com/t/array-sort-unexpected-behaviour/128799/1 "2008-02-11T17:48:33Z")

</div>

Please explain why “a” is corrupted after call to Array#sort:

irb(main):044:0\> a=[[1, “abc”],[3, “def”],[2, “efg”]]  
=\> [[1, “abc”], [3, “def”], [2, “efg”]]  
irb(main):045:0\> a.sort { |a, b| a[0] \<=\> b[0] }  
=\> [[1, “abc”], [2, “efg”], [3, “def”]]  
irb(main):046:0\> a  
=\> [1, “abc”]

A new sorted array is correctly returned, but “a” itself is not left  
intact.  
It seems to have something to do with me using an array-of-arrays.

/D

---

<div class="post-metadata">

**Author:** ![daniel\_SSSSkerud](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/8e8cbc/32.png) [@daniel\_SSSSkerud](https://www.ruby-forum.com/u/daniel_SSSSkerud)\
**Post date:** [February 11, 2008, 5:52pm UTC](https://www.ruby-forum.com/t/array-sort-unexpected-behaviour/128799/2 "2008-02-11T17:52:05Z")

</div>

On Feb 11, 2008, at 10:47 AM, daniel åkerud wrote:

> irb(main):044:0\> a=[[1, “abc”],[3, “def”],[2, “efg”]]  
> =\> [[1, “abc”], [3, “def”], [2, “efg”]]  
> irb(main):045:0\> a.sort { |a, b| a[0] \<=\> b[0] }  
> =\> [[1, “abc”], [2, “efg”], [3, “def”]]  
> irb(main):046:0\> a  
> =\> [1, “abc”]
> 
> A new sorted array is correctly returned, but “a” itself is not left  
> intact.  
> It seems to have something to do with me using an array-of-arrays.

Your block parameter is also called ‘a’.

In Ruby 1.9, this isn’t an issue, but in 1.8, the variable is the same  
as the block parameter.

Dave
