# 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}
=&gt; [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.

• Read “String” class documentation, in Ruby 1.9, you will find each_char, which will mean you don’t need to split the string, and then in the block do what you will do with each number to put it in the array.

Recommended: Read the String, Array, Hash and Enumerable documentation, as they will be used commonly.

The most concise thing I could think of, without obfuscation:

>> “123456789”.each_char.map {|c| c.to_i}
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

• irb(main):001:0> 1234567890.to_s.chars.map(&:to_i)

=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

• Tiffy

In Ruby 1.9.3 you can do the following to convert a String of Numbers to an Array of Numbers:

Without a space after the comma of split(‘,’) you get this:
“1,2,3”.split(‘,’) # => [“1″,”2″,”3”]

With a space after the comma of split(‘, ‘) you get this:
“1,2,3”.split(‘, ‘) # => [“1,2,3”]

Without a space after the comma of split(‘,’) you get this:
“1,2,3”.split(‘,’).map(&:to_i) # => [1,2,3]

With a space after the comma of split(‘, ‘) you get this:
“1,2,3”.split(‘, ‘).map(&:to_i) # => [1]