Reputation: 49
Running the following:
print ['1','2','3'].each { |j| j.to_i }
generates the output:
["1", "2", "3"]
I'd like to understand why it doesn't generate:
[1,2,3]
Thanks!
Upvotes: 2
Views: 60
Reputation: 306
Another way could be :
print ['1','2','3'].collect(&method(:Integer))
But note this can bring a downside to performance if you were to use in production..
Upvotes: 0
Reputation: 4226
Calling #each
on an applicable object will return that object after the function has finished looping, which is why you're getting the original array.
If you're looking to modify the values in the array, according to some rule, and return the result as a new array, you can use #map
:
arr = ['1', '2', '3']
arr.map {|j| j.to_i}
# => [1, 2, 3]
If you'd like to directly affect the original array, you can substitute the above with #map!
, which would mutate the original array.
Hope this helps!
Upvotes: 1
Reputation: 10951
Because .each
returns an original array. You have to use .map
['1','2','3'].map(&:to_i)
=> [1, 2, 3]
each definition:
rb_ary_each(VALUE array)
{
long i;
volatile VALUE ary = array;
RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
for (i=0; i<RARRAY_LEN(ary); i++) {
rb_yield(RARRAY_AREF(ary, i));
}
return ary; # returns original array
}
Upvotes: 2