Array#sort unexpected behaviour

Discussion in 'Ruby' started by daniel åkerud, Feb 11, 2008.

  1. [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
     
    daniel åkerud, Feb 11, 2008
    #1
    1. Advertising

  2. daniel åkerud

    Dave Thomas Guest

    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=
     
    Dave Thomas, Feb 11, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mark
    Replies:
    4
    Views:
    2,949
    scoude
    Jan 12, 2011
  2. rkk
    Replies:
    9
    Views:
    814
    CBFalconer
    Sep 24, 2006
  3. Navin
    Replies:
    1
    Views:
    701
    Ken Schaefer
    Sep 9, 2003
  4. GIMME
    Replies:
    5
    Views:
    187
    Thomas 'PointedEars' Lahn
    Jul 26, 2004
  5. Domenico Discepola

    multi-field array sort using Sort::Fields method

    Domenico Discepola, Apr 27, 2004, in forum: Perl Misc
    Replies:
    6
    Views:
    302
    Uri Guttman
    Apr 28, 2004
Loading...

Share This Page