On Wed, Nov 30, 2011 at 09:10, James Gallagher [email protected] wrote:

I don’t know how to split the individual digits up.

If you split on an empty delimiter, you get the characters
individually. E.g., “12345”.split(‘’) gives you [“1”, “2”, “3”, “4”,
“5”].

Let us know how you do with the “get the sum of the digits” problem.
It’s a good opportunity for you to learn some interesting concepts in
“functional programming” and some of the bizarrer-looking magic of
Ruby. See how short you can make the solution…

If the number of digits is less than five, how about this one for Ruby
Golf

“2011”.sum(48)%48

Regards,

Bill

Clever!

Is the parameter to sum even required in this case? The docs say the
parameter n merely limits the sum modulo 2**n-1 which defaults to 16,
or modulo 65535. And the number of digits could be more than five I’d
think, as the limiting factor is that modulo operation and so long as
the actual sum of each character does NOT cross that threshold (65535
in the default parameter case), it should be fine, no? (And using
ASCII values 48-57 inclusive, we should be safe at least up to strings
of 1149 digits in length.)

Thanks for teaching me yet another interesting tidbit of Ruby–I’d
never known about String#sum before.

Is the parameter to sum even required in this case? The docs say the
parameter n merely limits the sum modulo 2**n-1 which defaults to 16,
or modulo 65535. And the number of digits could be more than five I’d
think, as the limiting factor is that modulo operation and so long as
the actual sum of each character does NOT cross that threshold (65535
in the default parameter case), it should be fine, no? (And using
ASCII values 48-57 inclusive, we should be safe at least up to strings
of 1149 digits in length.)

First of all, to be more exact, I have to say in my previous post “if
the number of digits is less than or equal to five.”

I am assuming that we want the shortest code (for the Ruby Golf ).
Yes, you are right that with slightly longer code, we can deal with
larger number.

I Admin T.'s solution modified to support digit strings up to 1149
characters long (which is the path my muddled brain was meandering
down in my prior post):

irb(main):001:0> s=“2011”;s.sum%(48*s.size)
=> 4

And to verify worst-case a string of 1149 nine digits:

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

Of course using non-arabic UTF-8 encoded digits makes things very
intersting (a.k.a. fail), a la Devanagari digit six (the first
non-arabic UTF code point for a digit my search turned up):
0x096c.chr(Encoding::UTF_8) a.k.a. “\u096C”

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)
?