Matthew Moss ha scritto:
> ## Modular Arithmetic (#179)
>
> _Quiz idea provided by Jakub Ku┼║ma_
>
> [Modular][1] [arithmetic][2] is integer-based arithmetic in which the 
> operands and results are constrained to a limited range, from zero to 
> one less than the modulus. Take, for example, the 24-hour clock. Hours 
> on the clock start at 0 and increase up to (and include) 23. But above 
> that, we must use the appropriate congruent value modulo 24. For 
> example, if I wanted to know what time it would be seven hours after 
> 10pm, I would add 22 and 7 to get 29. As that is outside the range 
> `[0, 24)`, I take the congruent value mod 24, which is 5.  So seven 
> hours after 10pm is 5am.
>
> Your task this week is to write a class `Modulo` that behaves in 
> almost all ways like an `Integer`. It should support all basic 
> operations: addition, subtraction, multiplication, exponentiation, 
> conversion to string, etc. The significant difference, of course, is 
> that an instance of `Modulo` should act modularly.
>
> For example:
>
>    # The default modulus is 26.
>    > a = Modulo.new(15)
>    > b = Modulo.new(19)
>    > puts (a + b)
>    8
>    > puts (a - b)
>    22
>    > puts (b * 3)
>    5
>
> As noted in the example, you should use a modulus of 26 if none is 
> specified in the initializer.
>
> While most operations will be straightforward, modular division is a 
> bit trickier. [Here is one article][3] that explains how it can be 
> done, but I will leave division as extra credit.
>

Hi,

here's my solution:

class Modulo

  include Comparable

  [:+, :-, :*].each do |meth|
    define_method(meth) { |other_n| Modulo.new(@n.send(meth, 
other_n.to_i), @m) }
  end

  def initialize(n = 0, m = 26)
    @m = m
    @n = modularize(n)
  end

  def <=>(other_n)
    @n <=> other_n.to_i
  end

  def to_i
    @n
  end

  private

  def coerce(numeric)
    [@n, numeric]
  end

  def modularize(n)
    return (n > 0 ? n % @m : (n - @m) % @m) if (n - @m) >= 0 or n < 0
    n
  end

end

Please, refer to the git repository below for updated revisions of this 
solution.

http://github.com/remogatto/quizzes/tree/master/179/lib/modulo.rb

Bye.
Andrea