Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Array#sort unexpected behaviour

Reply
Thread Tools

Array#sort unexpected behaviour

 
 
daniel åkerud
Guest
Posts: n/a
 
      02-11-2008
[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

 
Reply With Quote
 
 
 
 
Dave Thomas
Guest
Posts: n/a
 
      02-11-2008

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=

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Unexpected behaviour for dispatching events... Mark Java 4 01-12-2011 04:21 PM
Unexpected behaviour Ioannis Vranos C++ 36 09-24-2004 03:49 PM
ostringstream unexpected behaviour Old Wolf C++ 1 02-04-2004 04:38 AM
Unexpected python behaviour Richard Philips Python 2 11-28-2003 03:14 PM
unexpected map behaviour Steven Van den Berghe C++ 2 08-28-2003 11:59 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57