[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Array#sort unexpected behaviour

daniel åkerud

2/11/2008 4:48:00 PM

[Note: parts of this message were removed to make it a legal post.]

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

1 Answer

Dave Thomas

2/11/2008 4:51:00 PM

0


On Feb 11, 2008, at 10:47 AM, daniel =E5kerud wrote:

> irb(main):044:0> a=3D[[1, "abc"],[3, "def"],[2, "efg"]]
> =3D> [[1, "abc"], [3, "def"], [2, "efg"]]
> irb(main):045:0> a.sort { |a, b| a[0] <=3D> b[0] }
> =3D> [[1, "abc"], [2, "efg"], [3, "def"]]
> irb(main):046:0> a
> =3D> [1, "abc"]
>
> A new sorted array is correctly returned, but "a" itself is not left =20=

> 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 =20=

as the block parameter.


Dave=