Даяна обнови решението на 15.01.2013 00:34 (преди около 12 години)
+require 'bigdecimal'
+require 'bigdecimal/util'
+
+class ExchangeRate
+ def initialize
+ @rate = {}
+ end
+
+ def set(from_currency, to_currency, rate)
+ return if to_currency == from_currency
+ if @rate.has_key?(from_currency) then @rate[from_currency][to_currency] = rate
+ else @rate[from_currency] = { to_currency => rate }
+ end
+ if @rate.has_key?(to_currency) then @rate[to_currency][from_currency] = 1 / rate
+ else @rate[to_currency] = { from_currency => 1 / rate }
+ end
+ end
+
+ def get(from_currency, to_currency)
+ return 1.to_d if from_currency == to_currency
+ @rate[from_currency][to_currency] if @rate[from_currency] and @rate[to_currency]
+ end
+
+ def convert(from_currency, to_currency, amount)
+ if from_currency == to_currency then amount.to_d
+ elsif not @rate[from_currency][to_currency] then raise RuntimeError, 'ExchangeRate::Unknown'
+ else amount * @rate[from_currency][to_currency].to_d
+ end
+ end
+end
+
+class Money
+ include Comparable
+ attr_reader :amount, :currency
+ def initialize(amount, currency)
+ @amount = amount
+ @currency = currency
+ end
+
+ def to_s
+ '%.2f' % @amount.to_s + " " + @currency.to_s
+ end
+
+ def in(currency, exchange_rate)
+ Money.new(exchange_rate.convert(@currency, currency, @amount), currency)
+ end
+
+ def errors(other, it_is_numeric = false)
+ if it_is_numeric then raise ArgumentError if not other.is_a? Numeric
+ elsif other.class != Money then raise ArgumentError
+ elsif other.currency != @currency then raise Money::IncompatibleCurrencies
+ end
+ end
+
+ def <=>(other)
+ errors(other)
+ @amount <=> other.amount
+ end
+
+ def +(other)
+ errors(other)
+ Money.new(@amount + other.amount, @currency)
+ end
+
+ def -(other)
+ errors(other)
+ Money.new(@amount - other.amount, @currency)
+ end
+
+ def *(number)
+ errors(number, true)
+ Money.new(@amount * number, @currency)
+ end
+
+ def /(number)
+ errors(number, true)
+ Money.new(@amount / number, @currency)
+ end
+end