Sha256: ce66c48e6d6e88d1ca07635063fa3b7d8244976c7a54abe6d17eeb47fd50abac

Contents?: true

Size: 1.19 KB

Versions: 109

Compression:

Stored size: 1.19 KB

Contents

#
# The ratio between two numbers (eg: 2:1, 3:4)
#
# Can be compared, added, "percent"ed, "to_f"ed, and displayed. 
#
class Ratio

  include Comparable

  def <=>(other)
    to_f <=> other.to_f
  end

  attr_accessor :first, :last

  def self.[](*args)
    new(*args)
  end

  #
  # `first` is the top part of the ratio, `last` is the bottom (eg: `first/last`)
  #
  def initialize(first, last=1)
    @first = first
    @last = last
  end

  #
  # Returns a string representation: "a/b"
  #
  def to_s
    "#{@first}/#{@last}"
  end
  alias_method :ratio, :to_s

  #
  # Returns the ratio as a float. (eg: Ratio[1,2].to_f == 0.5)
  #
  def to_f
    if @last == 0
      0.0
    else
      @first.to_f / @last
    end
  end

  #
  # Returns a string representing the number in percent
  #
  def percent
    "%0.1f%" % (to_f * 100)
  end
  alias_method :to_percent, :percent

  #
  # "#<Ratio: 1/2>"
  #
  def inspect
    "#<Ratio: #{to_s}>"
  end

  #
  # Adds together the tops and bottoms of the ratios.
  #
  # Example: For the ratios `a/c` and `b/d`, returns `a+b/c+d`
  #
  def +(other)
    Ratio.new( first+other.first, last+other.last)
  end

end

#
# Function-style wrapper
#
def Ratio(*args)
  Ratio.new(*args)
end

Version data entries

109 entries across 109 versions & 1 rubygems

Version Path
epitools-0.5.103 lib/epitools/ratio.rb
epitools-0.5.100 lib/epitools/ratio.rb
epitools-0.5.99 lib/epitools/ratio.rb
epitools-0.5.98 lib/epitools/ratio.rb
epitools-0.5.97 lib/epitools/ratio.rb
epitools-0.5.96 lib/epitools/ratio.rb
epitools-0.5.95 lib/epitools/ratio.rb
epitools-0.5.94 lib/epitools/ratio.rb
epitools-0.5.93 lib/epitools/ratio.rb
epitools-0.5.92 lib/epitools/ratio.rb
epitools-0.5.91 lib/epitools/ratio.rb
epitools-0.5.90 lib/epitools/ratio.rb
epitools-0.5.89 lib/epitools/ratio.rb
epitools-0.5.88 lib/epitools/ratio.rb
epitools-0.5.87 lib/epitools/ratio.rb
epitools-0.5.86 lib/epitools/ratio.rb
epitools-0.5.85 lib/epitools/ratio.rb
epitools-0.5.84 lib/epitools/ratio.rb
epitools-0.5.83 lib/epitools/ratio.rb
epitools-0.5.82 lib/epitools/ratio.rb