How To Convert A String Of Digits Or An Integer Into An Array Of Integers In Ruby

While figuring out how to solve Project Euler Problem 8, I was surprised to find that there isn’t really a quick method in Ruby for converting a string of digits or an integer into an array of integers in Ruby.

For example, let’s say you have a string of digits “123456789” or an integer 123456789 and need to convert it into the array [1, 2, 3, 4, 5, 6, 7, 8, 9], where each array object is an integer. How would you do it in Ruby?

Here is the answer I found to be most effective.


After looking around at a few forums and trying different things, this StackOverflow Answer was the most helpful:

Of course, the above answer is useful if you have a string of digits “123456789”. If you’re looking to convert an integer into an array of integers, make sure to convert your integer into a string first.

123456789.to_s.split(//).map{|chr| chr.to_i}
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Comment if you know of an even better way of doing this!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.