From: Tom Ha on
Hi there,

what's the most simple solution in Ruby to check if value x is a
multiple of y?

"if x/y.integer?"

...is obviously not the solution.

Thanks a lot!
Tom
--
Posted via http://www.ruby-forum.com/.

From: Stefano Crocco on
On Wednesday 21 July 2010, Tom Ha wrote:
> |Hi there,
> |
> |what's the most simple solution in Ruby to check if value x is a
> |multiple of y?
> |
> | "if x/y.integer?"
> |
> |...is obviously not the solution.
> |
> |Thanks a lot!
> |Tom

Assuming x and y are both integers, you can use the modulo operator:

if (x%y) == 0
...

Stefano

From: Xavier Noria on
On Wed, Jul 21, 2010 at 12:12 PM, Tom Ha <tom999(a)gmx.net> 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.

From: Tom Ha on
Thanks to everybody !
--
Posted via http://www.ruby-forum.com/.

From: Xavier Noria on
On Wednesday, July 21, 2010, Robert Klemme <shortcutter(a)googlemail.com> wrote:
> 2010/7/21 Xavier Noria <fxn(a)hashref.com>:
>> On Wed, Jul 21, 2010 at 12:12 PM, Tom Ha <tom999(a)gmx.net> 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) :-)