Милан обнови решението на 13.01.2013 17:14 (преди около 12 години)
+require 'bigdecimal'
+require 'bigdecimal/util'
+
+class ExchangeRate
+ def initialize
+ @rates = {}
+ @exchange = Struct.new(:first_currency, :second_currency)
+ end
+
+ def set(from_currency, to_currency, rate)
+ return if from_currency == to_currency
+
+ straight_exchange = @exchange.new from_currency, to_currency
+ reverse_exchange = @exchange.new to_currency, from_currency
+
+ @rates[straight_exchange] = rate
+ @rates[reverse_exchange] = 1 / rate
+ end
+
+ def get(from_currency, to_currency)
+ return BigDecimal.new('1') if from_currency == to_currency
+
+ exchange = @exchange.new from_currency, to_currency
+ @rates[exchange]
+ end
+
+ def convert(from_currency, to_currency, amount)
+ exchange = @exchange.new from_currency, to_currency
+ raise Unknown unless @rates.has_key? exchange
+
+ amount * @rates[exchange]
+ end
+
+ class Unknown < RuntimeError
+ end
+end
+
+class Money
+ include Comparable
+ attr_reader :amount, :currency
+
+ def initialize(amount, currency)
+ @amount, @currency = amount, currency
+ end
+
+ def in(currency, exchange_rate)
+ amount = exchange_rate.convert @currency, currency, @amount
+ self.class.new amount, currency
+ end
+
+ def to_s
+ ('%.2f' % @amount) + ' ' + currency.to_s
+ end
+
+ def <=>(other)
+ raise ArgumentError unless other.is_a? Money
+ raise IncompatibleCurrencies unless currency == other.currency
+
+ amount <=> other.amount
+ end
+
+ def +(other)
+ raise ArgumentError unless other.is_a? Money
+ raise IncompatibleCurrencies unless @currency == other.currency
+
+ self.class.new @amount + other.amount, @currency
+ end
+
+ def -(other)
+ raise ArgumentError unless other.is_a? Money
+ raise IncompatibleCurrencies unless currency == other.currency
+
+ self.class.new @amount - other.amount, @currency
+ end
+
+ def *(number)
+ raise ArgumentError unless number.is_a? Numeric
+
+ self.class.new @amount * number, @currency
+ end
+
+ def /(number)
+ raise ArgumentError unless number.is_a? Numeric
+
+ self.class.new @amount / number, @currency
+ end
+
+ class IncompatibleCurrencies < RuntimeError
+ end
+end