Тодор обнови решението на 16.01.2013 14:09 (преди около 12 години)
+require 'bigdecimal'
+require 'bigdecimal/util'
+include Comparable
+
+class ExchangeRate
+ def initialize
+ @rate_table = Hash.new
+ end
+
+ def set from_currency, to_currency, rate
+ @rate_table[[from_currency, to_currency]] = rate
+ @rate_table[[to_currency, from_currency]] = rate ** (-1)
+ end
+
+ def get from_currency, to_currency
+ if from_currency == to_currency then return '1'.to_d end
+ @rate_table[[from_currency, to_currency]]
+ end
+
+ def convert from_currency, to_currency, amount
+ rate = get from_currency, to_currency
+ rate * amount
+ end
+end
+
+class Money
+ attr_reader :amount, :currency
+
+ def initialize amount, currency
+ @amount = amount
+ @currency = currency
+ end
+
+ def to_s
+ amount_str = @amount.truncate(2).to_s('F')
+ if @amount.frac.to_s('F').length < 4 then amount_str << '0' end
+ amount_str + ' ' + @currency.to_s
+ end
+
+ def in new_currency, exchange_rate
+ new_amount = exchange_rate.convert @currency, new_currency, @amount
+ Money.new new_amount, new_currency
+ end
+
+ def * number
+ Money.new(@amount * number, @currency)
+ end
+
+ def / number
+ Money.new(@amount / number, @currency)
+ end
+
+ def - other
+ Money.new(@amount - other.amount, @currency)
+ end
+
+ def + other
+ Money.new(@amount + other.amount, @currency)
+ end
+
+ def <=> other
+ if @amount < other.amount
+ -1
+ elsif @amount == other.amount
+ 0
+ else
+ 1
+ end
+ end
+end