Емил обнови решението на 16.01.2013 16:13 (преди около 12 години)
+require 'bigdecimal'
+require 'bigdecimal/util'
+
+class ExchangeRate
+ class Unknown < RuntimeError
+ end
+
+ def initialize
+ @exchange_rates = {}
+ end
+
+ def set(from_currency, to_currency, rate)
+ unless from_currency == to_currency
+ @exchange_rates["#{from_currency}-#{to_currency}"] = rate
+ @exchange_rates["#{to_currency}-#{from_currency}"] = 1 / rate
+ end
+ end
+
+ def get(from_currency, to_currency)
+ if from_currency != to_currency
+ @exchange_rates["#{from_currency}-#{to_currency}"]
+ else
+ '1'.to_d
+ end
+ end
+
+ def convert(from_currency, to_currency, amount)
+ return amount if from_currency == to_currency
+ rate = @exchange_rates["#{from_currency}-#{to_currency}"]
+ if rate != nil
+ amount * rate
+ else
+ raise Unknown, "This convertion is unknown!"
+ end
+ end
+end
+
+class Money
+ attr_accessor :amount, :currency
+
+ def initialize(amount, currency)
+ @amount, @currency = amount, currency
+ end
+
+ def to_s
+ "#{'%.2f' % @amount} #{@currency}"
+ end
+
+ def in(currency, exchange_rate)
+ result_amount = exchange_rate.convert @currency, currency, @amount
+ Money.new result_amount, currency
+ end
+end