From: Tom Ha on 21 Jul 2010 06:12 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 21 Jul 2010 06:28 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 21 Jul 2010 06:31 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. From: Tom Ha on 21 Jul 2010 07:18 Thanks to everybody ! -- Posted via http://www.ruby-forum.com/. From: Xavier Noria on 21 Jul 2010 07:20 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) :-)  |  Next  |  Last Pages: 1 2 Prev: File class documentationNext: how to make "gem install rmagick" work?