money.rb
#!/usr/bin/ruby
class Money
attr_accessor :amount, :currency
protected :amount
def initialize(amount, currency)
@amount = amount
@currency = currency
end
def ==(other)
return @amount == other.amount && @currency == other.currency
end
def *(multiplier)
return Money.new(@amount * multiplier, @currency)
end
def self.franc(amount)
return Money.new(amount, "CHF")
end
def self.dollar(amount)
return Money.new(amount, "USD")
end
end
money_test.rb
#!/usr/bin/ruby
require 'test/unit'
require 'money'
class TestMoney < Test::Unit::TestCase
def test_multiplication
five = Money.dollar(5)
assert_equal(Money.dollar(10), five * 2)
assert_equal(Money.dollar(15), five * 3)
end
def test_equality
assert(Money.dollar(5) == Money.dollar(5))
assert(Money.dollar(5) != Money.dollar(6))
assert(Money.dollar(5) != Money.franc(5))
end
def test_currency
assert_equal("USD", Money.dollar(1).currency)
assert_equal("CHF", Money.franc(1).currency)
end
end