On Mon, Dec 5, 2011 at 12:17 PM, Sylvester K.
[email protected] wrote:
I posted a similar version to yours which uses an iterator.
Oh, I’m sorry I overlooked that one.
n = 2011
n.size.pred.downto(0).reduce(0) { |sum, a| sum += (n.abs / 10 ** a) % 10 }The while loop is more straightforward though. Perhaps we could combine the two?
I’m afraid your solution with Fixnum#size works only accidentally
because it returns the byte size of the number which coindicentally is
also the number of digits. It fails for other values:
n = 90000
=> 90000
n.size.pred.downto(0).reduce(0) { |sum, a| sum += (n.abs / 10 ** a) % 10 }
=> 0
n.size
=> 4
Kind regards
robert