mahatmanich
mahatmanich

Reputation: 11023

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.

Upvotes: 8

Views: 14861

Answers (5)

Mukesh Kumar Gupta
Mukesh Kumar Gupta

Reputation: 1647

There are multiple way, we can achieve it this.

  1. '12345'.chars.map(&:to_i)

  2. '12345'.split("").map(&:to_i)

  3. '12345'.each_char.map(&:to_i)

  4. '12345'.scan(/\w/).map(&:to_i)

I like 3rd one the most. More expressive and simple.

Upvotes: 3

Robin Wood
Robin Wood

Reputation: 41

In Ruby 1.9.3 you can do the following to convert a String of Numbers to an Array of Numbers:

Without a space after the comma of split(',') you get this: "1,2,3".split(',') # => ["1","2","3"]

With a space after the comma of split(', ') you get this: "1,2,3".split(', ') # => ["1,2,3"]

Without a space after the comma of split(',') you get this: "1,2,3".split(',').map(&:to_i) # => [1,2,3]

With a space after the comma of split(', ') you get this: "1,2,3".split(', ').map(&:to_i) # => [1]

Upvotes: 2

Ilya
Ilya

Reputation: 13487

You can use String#each_char:

array = []
s.each_char {|c| array << c.to_i }
array
#=> [2, 3, 5, 3, 4]

Or just s.each_char.map(&:to_i)

Upvotes: 3

Nobita
Nobita

Reputation: 23713

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.

Upvotes: 19

Alex
Alex

Reputation: 2518

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 }

Upvotes: 5

Related Questions