1

I want to convert a string into an array of integers. Why do I get an array of strings? What's the right way to achieve the result I'm looking for?

"1234".chars.each { |n| n.to_i }

=> ["1", "2", "3", "4"]

1 Answer 1

5

It's because each return the same array on which it was called. You need map here:

'1234'.chars.map(&:to_i)

which is a shorthand notation to:

'1234'.chars.map { |el| el.to_i }

and returns:

# => [1, 2, 3, 4]

As Cary Swoveland suggested, you can also use each_char method to prevent creation of additional array (each_char returns an enumerator):

'1234'.each_char.map(&:to_i)
Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps each_char to avoid the creation of a temporary array.
@CarySwoveland it's your idea. Why don't you add it as an alternative answer? :)
Because it is a tiny detail.

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.