mahatmanich mahatmanich - 2 years ago 150
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download