From: Robert Klemme Date: 2008-05-13T22:08:51+09:00 Subject: Re: Convert integer to array? 2008/5/13 Rob Biedenharn : > > > On May 13, 2008, at 7:26 AM, Robert Klemme wrote: > > > > 2008/5/12 Sebastian Hungerecker : > > > > > 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. The reasoning is wrong but comes to the right conclusion: if you want to retain the original value of x then it does not matter whether values are mutable or not. It is sufficient to assign to x to loose the original value. In my code I don't need y because x is a method parameter. My remark was a reaction to Sebastian's comment and piece of code which modified x. > 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. Exactly. :-) Kind regards robert -- use.inject do |as, often| as.you_can - without end