Stupid question

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

Admin T. wrote in post #1034521:

irb(main):002:0> s="9"1149;s.sum%(48s.size)
=> 10341

For longer strings, pass an argument to String#sum bigger than the
default 16.

Very good, Aaron. Now, is there any way to replace that “s.size” with
something to make it really a one-liner (without the semicolon):
“some number”.sum%(48 times something)
?

lambda {|x| x.sum%(48*x.size)}[“9”*1149]

Or something nasty with “->” if under ruby 1.9. But once you go to that
extreme, you might as well stick with the more obvious and complete:

(“9”*1149).chars.inject(0){|a,b|a+b.to_i}