2

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!

3
  • 1
    There's nothing wrong with this question, but upvotes?? Oh, wait, it must be a dup, as I've seen versions of it many, many times. Searching on "Ruby each vs map" brings up a bunch. Commented Oct 19, 2015 at 20:27
  • Searching "Ruby each vs map" is essentially working back from the answer to the question. Easy to do in hindsight only. Commented Oct 19, 2015 at 21:10
  • I wasn't criticizing you for not knowing that, but the idea is that when a question is a dup the asker need only be pointed to the answer. Note I said "there's nothing wrong with the question". We all have to start somewhere. Commented Oct 19, 2015 at 21:13

3 Answers 3

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

0

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.