Илиан обнови решението на 15.01.2013 22:49 (преди около 12 години)
+require 'bigdecimal'
+require 'bigdecimal/util'
+
+class ExchangeRate
+ class Unknown < RuntimeError
+ end
+
+ def initialize
+ @rates = {}
+ end
+
+ def set(from_currency, to_currency, rate)
+ return if from_currency == to_currency
+ @rates[from_currency.to_s + to_currency.to_s] = rate
+ @rates[to_currency.to_s + from_currency.to_s] = 1 / rate
+ end
+
+ def get(from_currency, to_currency)
+ return '1'.to_d if from_currency == to_currency
+ @rates[from_currency.to_s + to_currency.to_s]
+ end
+
+ def convert(from_currency, to_currency, amount)
+ rate = get(from_currency, to_currency)
+ raise ExchangeRate::Unknown if rate == nil
+ rate * amount
+ end
+end
+
+class Money
+ include Comparable
+ class IncompatibleCurrencies < RuntimeError
+ end
+
+ attr_reader :amount, :currency
+ def initialize(amount, currency)
+ #self.@amount, self.@currency = amount, currency
+ @amount, @currency = amount, currency
+ end
+
+ def to_s
+ @amount.round(2).to_s + ' ' + @currency.to_s
+ end
+
+ def in(currency, exchange_rate)
+ Money.new(exchange_rate.convert(@currency, currency, @amount), currency)
+ end
+
+ def *(multiplier)
+ raise ArgumentError, 'Invalid parameter type!' unless multiplier.kind_of? Numeric
+ Money.new @amount * multiplier, @currency
+ end
+
+ def /(divisor)
+ raise ArgumentError, 'Invalid parameter type!' unless divisor.kind_of? Numeric
+ Money.new @amount / divisor, @currency
+ self
+ end
+
+ def +(other)
+ raise ArgumentError, 'Invalid parameter type!' unless other.kind_of? Money
+ raise Money::IncompatibleCurrencies unless @currency == other.currency
+ Money.new @amount + other.amount, @currency
+ end
+
+ def -(other)
+ raise ArgumentError, 'Invalid parameter type!' unless other.kind_of? Money
+ raise Money::IncompatibleCurrencies unless @currency == other.currency
+ Money.new @amount - other.amount, @currency
+ end
+
+ def <=>(other)
+ raise ArgumentError, 'Invalid parameter type!' unless other.kind_of? Money
+ raise Money::IncompatibleCurrencies unless @currency == other.currency
+ @amount <=> other.amount
+ end
+end