On May 13, 2008, at 7:26 AM, Robert Klemme wrote:

> 2008/5/12 Sebastian Hungerecker <sepp2k / googlemail.com>:
>> Nadim Kobeissi wrote:
>>> Let's say I have:
>>> x=1234
>>> How can I convert that to the follow array:
>>> x=[1, 2, 3, 4]
>>
>> A solution that doesn't use strings:
>>
>> result_array = []
>> while x > 0
>>  result_array.unshift x % 10
>>  x /= 10
>> end
>> result_array
>>
>> This will "destroy" x, though.
>
> Well, that's easily fixed: just work with another variable.  You can
> also combine division and mod:
>
> def int_split(x)
>  r = []
>  y = x
>  while y > 0
>    y, b = y.divmod 10
>    r.unshift b
>  end
>  r
> end
>
> Kind regards
>
> robert
>
> --  
> use.inject do |as, often| as.you_can - without end

def int_split(x)
   return [0] if x.zero?
   r = []
   while x > 0
     x, b = x.divmod 10
     r.unshift b
   end
   r
end

You don't need y since Fixnums are immediate.  In fact, x is only a  
label, doing y=x just adds a new label to the object referred to by  
x.  (Go ahead, try it with a Bignum.)

It still doesn't work for negative numbers, but since that behavior  
hasn't been defined, it's left as an exercise for the OP.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com