suresh suresh - 4 months ago 11
Ruby Question

Splitting an interger into an array

I need to split the integer into an array.

For example,

The integer variable

a
equals
48
.

a = 48


I need to split the 48 into an array based on the count of 10.

I need to get the array as below,

arr = [ 10, 20, 30, 40, 48]


EDIT:-

I tried following code and it work fine.

max = 48
arr = []
j = 0
for i in 1..max
if i % 10 == 0
arr[j] = i
j = j + 1
end
end

if max % 10 != 0
arr[j] = max
end

p arr
# => [10, 20, 30, 40, 48]


But if I have a bignum integer it will take more time. Is there any built-in method to this like a split for string.

I know the split method and also I know how to split the string into an array based one the character available in the string. but I don't know how to use the split method splitting the integer into an array based on the count.

Any one please explain me how to do this ?

Thanks in advance!

Answer

Starting with a = 48 then try:

(10..a).step(10).to_a.push(a) #=> [10, 20, 30, 40, 48] 

Using Range#step to increment the range by steps of ten before converting to an array and finally appending your value of a.

Comments