class Money

Attributes

amount[RW]
currency[RW]

Public Class Methods

conversion_rates(base_currency, conversion_rates) click to toggle source
# File lib/money.rb, line 18
def self.conversion_rates(base_currency, conversion_rates)
              @@base_currency = base_currency
              @@conversion_rates = conversion_rates
      end
getRate(from_currency, to_currency) click to toggle source
# File lib/money.rb, line 83
def self.getRate(from_currency, to_currency)
  return 1 if to_currency == from_currency

  if !@@conversion_rates[to_currency].nil? && from_currency == @@base_currency
    return @@conversion_rates[to_currency]
  end

  if !@@conversion_rates[from_currency].nil? && to_currency == @@base_currency
    return 1.0 / @@conversion_rates[from_currency]
  end
end
new(amount, currency) click to toggle source

Constructor

# File lib/money.rb, line 13
def initialize(amount, currency)
  @amount = amount.to_f
  @currency = currency
end

Public Instance Methods

*(number) click to toggle source
# File lib/money.rb, line 51
def *(number)
  Money.new(self.amount * number.to_f, self.currency)
end
+(other) click to toggle source
# File lib/money.rb, line 43
def +(other)
  Money.new(self.amount + other_amount(other), self.currency)
end
-(other) click to toggle source
# File lib/money.rb, line 47
def -(other)
  Money.new(self.amount - other_amount(other), self.currency)
end
/(number) click to toggle source
# File lib/money.rb, line 55
def /(number)
  Money.new(self.amount / number.to_f, self.currency)
end
<(other) click to toggle source
# File lib/money.rb, line 70
def <(other)
  temp = other.convert_to(self.currency)
  self.amount.round(2) < temp.amount.round(2)
end
==(other) click to toggle source

Comparisons

# File lib/money.rb, line 60
def ==(other)
  temp = other.convert_to(self.currency)
  self.amount.round(2) == temp.amount.round(2)
end
>(other) click to toggle source
# File lib/money.rb, line 65
def >(other)
  temp = other.convert_to(self.currency)
  self.amount.round(2) > temp.amount.round(2)
end
convert_to(to_currency) click to toggle source

Convert method

# File lib/money.rb, line 24
def convert_to(to_currency)
  if @@conversion_rates[to_currency].nil?
    puts 'Rate not found'
  else
    from_currency = self.currency
    rate = Money.getRate(from_currency, to_currency)
  
    converted_amount = self.amount * rate

    Money.new(converted_amount, to_currency)
  end
end
inspect() click to toggle source
# File lib/money.rb, line 75
def inspect
  sprintf('%.2f %s', amount, currency)
end
other_amount(other) click to toggle source

Arithmetics

# File lib/money.rb, line 38
def other_amount(other)
  rate = Money.getRate(other.currency, self.currency)
  other.amount * rate
end
to_s() click to toggle source
# File lib/money.rb, line 79
def to_s
  sprintf('%.2f %s', amount, currency)
end