Array#each, safe when modifying it's elements?

Discussion in 'Ruby' started by Onion Knight, Mar 5, 2007.

  1. Onion Knight

    Onion Knight Guest

    Will Array#each only go through each unique element once even if you
    were to throw around the elements in the array or will it just take
    whatever element is after the current one?
    I tried it myself but it behaves a bit strange.

    a = [1, 2, 3, 4, 5, 6, 7]
    a.each do |x|
    print x
    if x == 2
    a.reverse!
    end
    end

    It prints 1254327. Somehow the last element was intact and printed a 7
    instead of 1.

    --
    Posted via http://www.ruby-forum.com/.
    Onion Knight, Mar 5, 2007
    #1
    1. Advertising

  2. Onion Knight

    Onion Knight Guest

    No wait I'm dumb, there's a second 2 at the end so the array get
    reversed again. I guess it proves it isn't intact though. To solve that
    I'm thinking that I could just copy the array and use that copy for
    iteration.

    --
    Posted via http://www.ruby-forum.com/.
    Onion Knight, Mar 5, 2007
    #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. Tjerk Wolterink

    xsl:for-each for each 3 elements problem

    Tjerk Wolterink, Nov 3, 2004, in forum: XML
    Replies:
    3
    Views:
    412
    Tjerk Wolterink
    Nov 3, 2004
  2. Paul Paterson

    How safe is modifying locals()?

    Paul Paterson, Jul 25, 2003, in forum: Python
    Replies:
    15
    Views:
    477
    Corey Coughlin
    Jul 28, 2003
  3. Pat Maddox
    Replies:
    6
    Views:
    132
    Marcin Mielżyński
    Jan 20, 2006
  4. Glenn Ritz
    Replies:
    3
    Views:
    88
    Glenn Ritz
    Mar 20, 2010
  5. fenisol3

    Modifying elements of an array

    fenisol3, Apr 2, 2004, in forum: Perl Misc
    Replies:
    2
    Views:
    92
    Paul Lalli
    Apr 2, 2004
Loading...

Share This Page