Randomtheories
Randomtheories

Reputation: 1290

Ruby: string to array of integers

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"]

Upvotes: 1

Views: 94

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51191

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)

Upvotes: 5

Related Questions