0

I have noticed strange behavior. While this one runs as expected:

@a = ['0','1','2','3','4','5']
def test2
  @a[0..2].each do |i|
    puts 'I am at: ' +i.to_s
    if i == '2'
      puts 'I am removing 2'
      @a.delete(i)
      licz
    end
  end
end


I am at: 0
I am at: 1
I am at: 2
I am removing 2
I am at: 0
I am at: 1
I am at: 3

Somehow, this code, 'remembers' old array and tries to finish previous 'if' statement:

@a = ['0','1','2','3','4','5']
def test1
  @a.each do |i|
    puts 'I am at: ' +i.to_s
    if i == '2'
      puts 'I am removing 2'
      @a.delete(i)
      test1
    end
  end
end
    I am at: 0
    I am at: 1
    I am at: 2
    I am removing 2
    I am at: 0
    I am at: 1
    I am at: 3
    I am at: 4
    I am at: 5
    I am at: 4
    I am at: 5
    => ["0", "1", "3", "4", "5"]

Why does it repeat 4 5, 4 5 ?

I am aware that in second test, I run each on each element, but why it tries to finish old statement?

2
  • 1
    Because you're calling this method recursively. Commented May 13, 2012 at 15:46
  • just noticed that. lol, to much of coding for the weekend ;) Commented May 13, 2012 at 15:50

1 Answer 1

3

Because you call the same function (test1) twice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.