Hi:
I am a newbie as far as Ruby is concerned. I was going through the
programming ruby book (2nd Edition), but was not able to figure out the
difference between the 2 statements:
[1, 2, 3, 4].collect{[i] puts i }
and
[1, 2, 3, 4].each{|i| puts i }
On Oct 27, 2005, at 8:17 PM, vasten@gmail.com wrote:
Hi:
I am a newbie as far as Ruby is concerned. I was going through the
programming ruby book (2nd Edition), but was not able to figure out the
difference between the 2 statements:
[1, 2, 3, 4].collect{[i] puts i }
and
[1, 2, 3, 4].each{|i| puts i }
Can some guru in this group shed some light?
------------------------------------------------------------------------
Returns a new array with the results of running _block_ once for
every element in _enum_.
Hi:
I am a newbie as far as Ruby is concerned. I was going through the
programming ruby book (2nd Edition), but was not able to figure out the
difference between the 2 statements:
[1, 2, 3, 4].collect{[i] puts i }
and
[1, 2, 3, 4].each{|i| puts i }
Can some guru in this group shed some light?
Thanks.
#collect applies the block on each value of the array, and *returns the result of the expression as an array for each value*. #each applies the block on each value of the array, but *returns the unmodified array*. #collect is used for the effect it has on the array, #each is just used for looping.
You can't see the difference here because you are not catching the array returned by #collect. Usually one would do:
result = [1,2,3,4].collect{|i| do_something(i)}
while leaving #each the way you did it.
In article <1130469173.146954.208420@g49g2000cwa.googlegroups.com>,
vasten@gmail.com writes:
Hi:
I am a newbie as far as Ruby is concerned. I was going through the
programming ruby book (2nd Edition), but was not able to figure out the
difference between the 2 statements:
[1, 2, 3, 4].collect{[i] puts i }
I guess that should read [1, 2, 3, 4].collect{|i| puts i }
and
[1, 2, 3, 4].each{|i| puts i }
Can some guru in this group shed some light?
run it in irb and you'll see, that your collect statement returns an
array of nils ( [nil, nil, nil, nil] ) while the each statement returns
the initial array ( [1, 2, 3, 4] )
I'm not a guru but AFAIK this is since collect returns an array created
from the return values of the block (puts returns nil) while each returns
the array it's called on.