From: w wg Date: 2008-09-27T16:55:20+09:00 Subject: Re: How does Array's each method change its elements ? I have noticed that Number elements and String elements of an array generate diffrent results in its EACH method if you change the elements. But it is difficult to understand how ruby implements arrays each method block. 2008/9/26 Peņa, Botp : > From: w wg [mailto:duzuike@gmail.com] > #.. > # a = ["how","are","you"] > # b = a.each { |x| x << "-" } > # puts a > # ["how-","are-","you-"] > # puts b > # ["how-","are-","you-"] > # > # The array changed! > # > # I want to know how does Array's each method (block) change > # its elements ? > > each just iterates on each element/object of the array. an array is just a container of objects (wc includes also arrays). if you use << or concat method, you change the object, ergo, you change the array too. > > try array#map and just use simple + for concatenation, eg > >> a > => ["how", "are", "you"] > >> c = a.map{ |x| x + "-" } > => ["how-", "are-", "you-"] > >> a > => ["how", "are", "you"] > >> c > => ["how-", "are-", "you-"] > > also note, strings are mutable objects, but, numbers are not. > see, > >> a=[1,2,3] > => [1, 2, 3] > >> b=a.each{|x| x+=1} > => [1, 2, 3] > >> a > => [1, 2, 3] > >> b > => [1, 2, 3] > > no change > the expression x+=1 seems to change the object pointed by var x. but no. a new object (eg 2) is now pointed by x, wc is outside of the array. ruby cannot change the object 1. for ruby, 1 is always 1. Since we did not do anything on the new objects 2,3,4, they just get lost/cleanuped. They were there before. You can print them if you're in doubt. But you can save them easily if you use array#map. > > let's use again map > >> b=a.map{|x| x+=1} > => [2, 3, 4] > >> a > => [1, 2, 3] > >> b > => [2, 3, 4] > > hth > kind regards -botp > > -- -- WenGe Wang