Sha256: 264a954736fcf369ebcc646fa44556c1532d39a6371cdc3e0bba3cfc30c50733

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

module Mext
  module Numeric

    #
    # +Meter+:
    #
    # in music we cannot use the +Rational+ class
    # because the latter will make all due conversions
    # simplifying meters (like: 4/4 => 1/1), which is not what we want
    #
    class Meter
  
      attr_accessor :numerator, :divisor

      alias_method :denominator, :divisor
  
      def initialize(n, d)
        self.numerator = n.to_f
        self.divisor   = d.to_f
      end

      def to_r
        Rational(self.numerator, self.divisor)
      end

      def to_s
        "#{self.numerator}/#{self.divisor}"
      end
      #
      # we use the logic of +Rational+ to perform logic on +Meter+
      #
      [:==, :<, :<=, :>, :>=, :<=>, :===].each { |m| define_method(m) { |other| common_logic(m, other) } }

    private

      def common_logic(method, other)
        raise ArgumentError unless other.kind_of?(Meter) || other.kind_of?(Rational)
        self.to_r.send(method, other.to_r)
      end
  
    end

  end
end

#
# +Meter(n, d)+ is defined to actually mimick a +Rational()+
#
def Meter(n, d)
  Mext::Numeric::Meter.new(n,d)
end

#
# we extend the +String+ class to carry a +to_meter+ which
# will convert a string into a meter
#
class String

  def to_meter
    div = num = 1.0
    (nums, divs) = self.split(/\s*\/\s*/, 2)
    num = nums.to_f
    div = divs.to_f
    Meter(num, div)
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ruby-mext-0.21.1 lib/mext/numeric/meter.rb