mahatmanich mahatmanich - 10 months ago 46
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
or even have the string be represented as a char array as in Java, and then convert all chars

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.


A simple one liner would be:
#=> [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: { |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.