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!
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!
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
}
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!