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.
Strings can be converted to arrays using a combination of the split method and some regular expressions. The split method serves to break up the string into distinct parts that can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.
Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
The to_s function in Ruby returns a string containing the place-value representation of int with radix base (between 2 and 36). If no base is provided in the parameter then it assumes the base to be 10 and returns.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With