Convert string to int array in Ruby

12,148

Solution 1

A simple one liner would be:

s.each_char.map(&:to_i)
#=> [2, 3, 5, 3, 4]

If you want it to be error explicit if the string is not contained of just integers, you could do:

s.each_char.map { |c| Integer(c) }

This would raise an ArgumentError: invalid value for Integer(): if your string contained something else than integers. Otherwise for .to_i you would see zeros for characters.

Solution 2

Short and simple:

"23534".split('').map(&:to_i)

Explanation:

"23534".split('') # Returns an array with each character as a single element.

"23534".split('').map(&:to_i) # shortcut notation instead of writing down a full block, this is equivalent to the next line

"23534".split('').map{|item| item.to_i }

Solution 3

You can use String#each_char:

array = []
s.each_char {|c| array << c.to_i }
array
#=> [2, 3, 5, 3, 4]

Or just s.each_char.map(&:to_i)

Solution 4

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]

Solution 5

There are multiple way, we can achieve it this.

  1. '12345'.chars.map(&:to_i)

  2. '12345'.split("").map(&:to_i)

  3. '12345'.each_char.map(&:to_i)

  4. '12345'.scan(/\w/).map(&:to_i)

I like 3rd one the most. More expressive and simple.

Share:
12,148
mahatmanich
Author by

mahatmanich

Updated on June 22, 2022

Comments

  • mahatmanich
    mahatmanich almost 2 years

    How do I convert a String: s = '23534' to an array as such: a = [2,3,5,3,4]

    Is there a way to iterate over the chars in ruby and convert each of them to_i or even have the string be represented as a char array as in Java, and then convert all chars to_i

    As you can see, I do not have a delimiter as such , in the String, all other answers I found on SO included a delimiting char.

  • mahatmanich
    mahatmanich about 8 years
    ahhhh each_char to the rescue ... exactly what I overlooked in the string api ...
  • steenslag
    steenslag over 5 years
    '23534'.to_i.digits.reverse