From: Robert Klemme Date: 2010-07-22T02:45:07+09:00 Subject: Re: How to check if x is a multiple of y On 21.07.2010 13:20, Xavier Noria wrote: > On Wednesday, July 21, 2010, Robert Klemme wrote: >> 2010/7/21 Xavier Noria: >>> On Wed, Jul 21, 2010 at 12:12 PM, Tom Ha wrote: >>> >>>> what's the most simple solution in Ruby to check if value x is a >>>> multiple of y? >>> >>> That's typically done with the modulus operator, Active Support >>> defines it this way >>> >>> class Integer >>> # Check whether the integer is evenly divisible by the argument. >>> def multiple_of?(number) >>> number != 0 ? self % number == 0 : zero? >>> end >>> end >>> >>> It is special-cased because you can't do modulus 0. >> >> I see a benchmark lurking: that version vs. this one. >> >> class Integer >> def multiple_off? number >> zero? || self % number == 0 >> end >> end >> >> :-) > > But that one is not well-defined for 1.multiple_of?(0) :-) There you see why posting in a hurry is a bad idea. Thanks for catching that. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/