Reputation: 1290
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
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