array.each

P

Phillip Curry

[Note: parts of this message were removed to make it a legal post.]

I want to take an array of strings and convert each member to an integer.
array.to_i obviously doesn't work.
I tried array.each { |x| x = x.to_i } and that doesn't work either.
aray.each_index { |x| array[x] = array[x].to_i } works fine. I'm finding
that pretty much every time I try to use each, each_index works better. Why
doesn't each work here, is there anything I can do about it, and is there
anything in particular that each does better than each_index or should I
just drop it entirely?

thanks
phil
 
A

Alex DeCaria

Phillip said:
I want to take an array of strings and convert each member to an
integer.
array.to_i obviously doesn't work.
I tried array.each { |x| x = x.to_i } and that doesn't work either.
aray.each_index { |x| array[x] = array[x].to_i } works fine. I'm
finding
that pretty much every time I try to use each, each_index works better.
Why
doesn't each work here, is there anything I can do about it, and is
there
anything in particular that each does better than each_index or should I
just drop it entirely?

thanks
phil

The issue is one of scope of local variables. x is a block parameter,
and is local to the block. That is why when you change the value of x
within the block, it has no affect on array. Each time the block
executes, the value of an element in array is copied to x, but changing
x doesn't change the value of array. The .each_index method works
because array was initialized outside of the block and is available
within within the block itself (but x itself is still local to the
block).

There are times when .each is appropriate, but for what you are doing,
each_index is what you need.
-Alex
 
G

Gary Wright

Gary said:
I want to take an array of strings and convert each member to an integer.
array.to_i obviously doesn't work.

=> a = %w{1 2 3 4}
=> ["1", "2", "3", "4"]
a.map! { |x| x.to_i }
=> [1, 2, 3, 4]

simply
["1","2"].collect(&:to_i)

simply?

Your alternative creates a new array and it seemed like the OP
wanted to replace the elements in the existing array. And I don't
think Symbol#to_proc is 'simple' for someone who isn't familiar yet
with map/map! (or collect/collect!).

Gary Wright
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top