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

10 Dec

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!

Advertisements

One Response to “How To Convert A String Of Digits Or An Integer Into An Array Of Integers In Ruby”

  1. Vic (@kotp) December 29, 2011 at 10:34 pm #

    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]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s