On Thu, Apr 7, 2011 at 8:34 PM, 7stud – [email protected] wrote:
each() doesn’t create a new array. Why not use map()? And you need to
be careful using delete!() because it will change the strings in the
original array too.
This obviously depends on what he needs. The fact that each doesn’t
create a new array can be a good thing :-).
array = [“hel\nlo”, “bl\nah”]
new_arr = array.map do |str|
str.delete!(“\n”)
end
This I don’t understand. You are modifying the original strings but
creating a new array with them. What could be the use case for this?
the strings. On the other hand, if you don’t need two versions of the
array hanging around in memory, then use all ! methods:
array = [“hel\nlo”, “bl\nah”]
array.map! do |str|
str.delete!(“\n”)
end
You don’t need map! here, cause you don’t want to change which object
each position references. You just want to modify the strings
themselves. What I would say is that, if you need to preserve the
original strings (because they are referenced by other variables) but
use the same array, do:
a = “hel\nlo”
b = “bl\nah”
array = [a,b]
array.map! do |str|
str.delete(“\n”)
end
The bang version of map, because you want to change the array, but the
non-bang version of delete so as to keep the original strings. The two
cases you propose above have less use cases, IMHO.
Jesus.