w wg
9/27/2008 7:55:00 AM
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=F1a, Botp <botp@delmonte-phil.com>:
> From: w wg [mailto:duzuike@gmail.com]
> #..
> # a =3D ["how","are","you"]
> # b =3D 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 m=
ethod, you change the object, ergo, you change the array too.
>
> try array#map and just use simple + for concatenation, eg
>
>> a
> =3D> ["how", "are", "you"]
>
>> c =3D a.map{ |x| x + "-" }
> =3D> ["how-", "are-", "you-"]
>
>> a
> =3D> ["how", "are", "you"]
>
>> c
> =3D> ["how-", "are-", "you-"]
>
> also note, strings are mutable objects, but, numbers are not.
> see,
>
>> a=3D[1,2,3]
> =3D> [1, 2, 3]
>
>> b=3Da.each{|x| x+=3D1}
> =3D> [1, 2, 3]
>
>> a
> =3D> [1, 2, 3]
>
>> b
> =3D> [1, 2, 3]
>
> no change
> the expression x+=3D1 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 a=
nything on the new objects 2,3,4, they just get lost/cleanuped. They were t=
here before. You can print them if you're in doubt. But you can save them e=
asily if you use array#map.
>
> let's use again map
>
>> b=3Da.map{|x| x+=3D1}
> =3D> [2, 3, 4]
>
>> a
> =3D> [1, 2, 3]
>
>> b
> =3D> [2, 3, 4]
>
> hth
> kind regards -botp
>
>
--=20
--
WenGe Wang