8

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.

5 Answers 5

19

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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 }

Comments

3

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)

1 Comment

ahhhh each_char to the rescue ... exactly what I overlooked in the string api ...
3

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.

1 Comment

'23534'.to_i.digits.reverse
2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.