0

How to split a number into an array of its digits?

123 should become [1,2,3]

I found this thread in the Ruby forum when I was looking for an idiomatic solution to the question above. The solutions there are working for me and they seem fine, I am using .to_s.chars.map(&:to_i)

But the thread is quite old, and I want to known if there are better, maybe newer ways to solve the task, given that Ruby as a language has developed further?

Known solutions:

.to_s.chars.map(&:to_i)

12345.to_s.scan(/./)

How do you solve it? Why? To me as a beginner, seeing different ways to solve a problem helps a lot to understand the language and its use better. So, thanks for your input!

Flip
  • 6,233
  • 7
  • 46
  • 75
  • 1
    What's wrong with `chars.map(&:to_i)`? It works. If you're using that frequently enough it's an irritation make a method that does it for you. – tadman Sep 27 '16 at 16:46
  • As I said, nothing wrong with it. On the contrary, I like it. I am just wondering if there are more ways. – Flip Sep 27 '16 at 16:49
  • That's a pretty minimal approach, but if you want you can extend Integer to have a method called `digits` that does this. – tadman Sep 27 '16 at 17:22
  • Well the numbers are in denary so you could deconstruct them with this in mind. – Sagar Pandya Sep 27 '16 at 17:25
  • We don't need a second question for the "best" answer, and your titles shouldn't include "best" in them. The "best" is implied by asking the question; obviously you're interested in the *best* answer or we wouldn't have a system where voting causes the higher-voted answers to bubble upwards. – user229044 Sep 27 '16 at 17:28

0 Answers0