From: "Peña, Botp" Date: 2008-09-26T18:56:03+09:00 Subject: Re: How does Array's each method change its elements ? 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