Link - 2 years ago 76

Ruby Question

Possible Duplicate:

Turning long fixed number to array Ruby

Well, I have to iterate over the digits of a integer in Ruby. Right now I was just splitting it up into an array, and then iterating over that. However I was wondering if there was a faster way to do this?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The shortest solution probably is:

```
1234.to_s.chars.map(&:to_i)
#=> [1, 2, 3, 4]
```

Here's a more orthodox mathematical approach:

```
class Fixnum
def digits(base: 10)
quotient, remainder = divmod(base)
quotient == 0 ? [remainder] : [*quotient.digits(base: base), remainder]
end
end
1234.digits #=> [1, 2, 3, 4]
0644.digits(base: 8) #=> [6, 4, 4]
0x3f.digits(base: 16) #=> [3, 15]
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**