Чанита обнови решението на 13.01.2013 23:01 (преди около 12 години)
+require 'bigdecimal'
+require 'bigdecimal/util'
+
+class ExchangeRate
+
+ class Unknown < RuntimeError
+ end
+
+ def initialize()
+ @hash = Hash.new { |hash, key| hash[key] = [[key,(BigDecimal.new '1.0')]] }
+ end
+
+ def set(from_currency, to_currency, rate)
+ return if(from_currency == to_currency)
+ @hash[from_currency] << [to_currency,rate]
+ @hash[to_currency] << [from_currency,BigDecimal("1.0")/rate]
+ end
+
+ def get(from_currency, to_currency)
+ @hash[from_currency].map{|x| return x[1] if(x[0] == to_currency)}
+ nil
+ end
+
+ def convert(from_currency, to_currency, amount)
+ @hash[from_currency].map{ |x| return amount*x[1] if(x[0] == to_currency)}
+ raise Unknown
+ end
+
+end
+
+class Money
+ include Comparable
+
+ attr_reader :amount, :currency
+
+ class IncompatibleCurrencies < RuntimeError
+ end
+
+ def initialize(amount, currency)
+ @amount = amount
+ @currency = currency
+ end
+
+ def to_s
+ return amount.round(2).to_s('F') + "0 " + currency.to_s if(amount.frac == 0)
+ amount.round(2).to_s('F') + " " + currency.to_s
+ end
+
+ def in(currency, exchange_rate)
+ Money.new(exchange_rate.convert(self.currency,currency,amount),currency)
+ end
+
+ def *(other)
+ raise ArgumentError unless(other.kind_of? Numeric)
+ Money.new(amount * other, currency)
+ end
+
+ def /(other)
+ raise ArgumentError unless(other.kind_of? Numeric)
+ Money.new(amount / other, currency)
+ end
+
+ def +(other)
+ raise ArgumentError unless(other.instance_of? Money)
+ raise IncompatibleCurrencies if(currency != other.currency)
+ Money.new(amount + other.amount, currency)
+ end
+
+ def -(other)
+ raise ArgumentError unless(other.instance_of? Money)
+ raise IncompatibleCurrencies if(currency != other.currency)
+ Money.new(amount - other.amount, currency)
+ end
+
+ def <=>(other)
+ raise ArgumentError if(!other.instance_of? Money)
+ raise IncompatibleCurrencies if(currency != other.currency)
+ amount <=> other.amount
+ end
+
+ def ==(other)
+ raise ArgumentError if(!other.instance_of? Money)
+ raise IncompatibleCurrencies if(currency != other.currency)
+ amount == other.amount
+ end
+
+end