From: 7stud -- Date: 2012-09-20T13:43:21+09:00 Subject: Re: the behavior of iterator methods Well, let's take a look at the docs: http://www.ruby-doc.org/core-1.9.3/Array.html Hmm....the typically crummy ruby docs are no help: each() returns an array--but what array?? We'll have to figure things out for ourselves: x = [1, 2, 3] puts x.object_id result = x.each {|num| num += 1} p result puts result.object_id --output:-- 2152279020 [1, 2, 3] 2152279020 So each() just returns the original array. > So I thought if variable named 'i' > changed its value, that had to be reflected to the Array > object 'a'. But it didn't. i is a local variable to the block. each() assigns each value in the array to the variable i. Then you add 1 to i, then the block ends and the variable i is destroyed. That has no effect on the original array. Here is a simpler example of how that works: x = [1, 2, 3] z = x[0] z += 10 p x --output:-- [1, 2, 3] Ruby numbers are immutable so when you write z += 10, that is equivalent to z = z + 10, and ruby takes the value of z, which is 1, and the value 10 and creates a new Integer object whose value is 11, then the new Integer object gets assigned to z. That doesn't affect the Integer object, i.e 1, that x[0] refers to. To affect the original array, you would have to do this: x = [1, 2, 3] x.length.times {|i| x[i] += 1} p x --output:-- [2, 3, 4] -- Posted via http://www.ruby-forum.com/.