mahatmanich mahatmanich - 7 months ago 25
Ruby Question

Convert string to int array in Ruby

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.

Answer

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.