Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 699
mahatmanich Avatar asked Apr 17 '16 20:04

mahatmanich


People also ask

How do I convert a string to an array in Ruby?

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.

How do you convert an array of strings to integers in Ruby?

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.

What does .select do in Ruby?

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.

What is TO_S in Ruby?

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.


2 Answers

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.

like image 77
Nobita Avatar answered Sep 28 '22 16:09

Nobita


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 }
like image 39
Alex Avatar answered Sep 28 '22 17:09

Alex