> Apparently inside an "each" loop you're only working
> on a copy of the
> item, not the item itself, so to_s isn't actually
> working on the real
> items in the array.

This is not true. The problem is not that you have a copy, but rather that your 
reference ('item") is local to the block. Changing it doesn't change anything 
outside the block. The problem isn't with what you are given in the block, but 
rather with what you are doing with it.

> aoa = [[1,2,3],[4,5,6]]

> aoa.each do |arr|
> arr.each do |item|
> item = item.to_s
> end 

> To make this work, you have to use "map":
> 
> aoa.each do |arr|
>        arr.map! do |item|
>         item = item.to_s
>        end

Note that "item" is a local variable and that therefore changing its value has 
absolutely no effect. In other words, this code does exactly the same thing:

 aoa.each do |arr|
        arr.map! do |item|
           item.to_s
        end

Your post suggested that "map!" increases the scope of the bound variable. But 
actually what it does is replace the item in arr with the value returned by the 
block. A side effect of assignment is that it returns the value, and that is 
what is actually doing the work.

Bret
---------------------------------------------------------------------
Posted via Jive Forums
http://forums.openqa.org/thread.jspa?threadID=6791&messageID=19606#19606
_______________________________________________
Wtr-general mailing list
Wtr-general@rubyforge.org
http://rubyforge.org/mailman/listinfo/wtr-general

Reply via email to