Светлана обнови решението на 16.01.2013 16:40 (преди около 12 години)
+ require 'bigdecimal'
+ require 'bigdecimal/util'
+
+ class ExchangeRate
+ attr_accessor :rates
+
+ def initialize()
+ @rates = {}
+ end
+
+ def set(from_currency, to_currency, rate)
+ rates[[from_currency, to_currency]]=rate
+ rates[[to_currency, from_currency]]=1/rate
+ if from_currency == to_currency
+ rates[[to_currency, from_currency]]=1
+ end
+ end
+
+ def get(from_currency, to_currency)
+ rates[[from_currency, to_currency]]
+ end
+
+ def convert(from_currency, to_currency, amount)
+ rate = rates[[from_currency, to_currency]]
+ if !rate
+ raise Unknown
+ end
+ amount*rate
+ end
+
+ class Unknown < RuntimeError
+
+ def exception
+ end
+
+ end
+
+ end
+
+ class Money
+ include Comparable
+ attr_accessor :amount, :currency
+
+ def initialize(amount, currency)
+ @amount = amount.to_d
+ @currency = currency
+ end
+
+ def to_s
+ s = amount.ceil(2).to_s(' f')
+ if s.index('.')<s.length
+ s = s + '0'
+ end
+ s = s[1..s.index('.')+2] + ' ' + currency.to_s
+ end
+
+ def in(currency, exchange_rate)
+ new_amount = exchange_rate.convert(self.currency, currency, amount)
+ Money.new new_amount, currency
+ end
+
+ def *(number)
+ if ! number.kind_of?(Numeric)
+ raise ArgumentError
+ end
+ Money.new amount*number, currency
+ end
+
+ def /(number)
+ if ! number.kind_of?(Numeric)
+ raise ArgumentError
+ end
+ Money.new amount/number, currency
+ end
+
+ def +(money)
+ if !money.instance_of?(Money)
+ raise ArgumentError
+ end
+ if currency != money.currency
+ raise IncompatibleCurrencies
+ end
+ Money.new amount + money.amount, currency
+ end
+
+ def -(money)
+ if !money.instance_of?(Money)
+ raise ArgumentError
+ end
+ if currency != money.currency
+ raise IncompatibleCurrencies
+ end
+ Money.new amount - money.amount, currency
+ end
+
+ def <=> (other)
+ if !other.instance_of?(Money) then raise ArgumentError end
+ if other.currency != currency then raise IncompatibleCurrencies end
+ if amount == other.amount then return 0 end
+ if amount > other.amount then return 1 end
+ -1
+ end
+
+ class IncompatibleCurrencies < StandardError
+
+ def exception
+ end
+
+ end
+
+ end