10章で実施したこと
- *()メソッドをMoneyクラスに移動
結局Pythonの__repr__()メソッドに相当するメソッドが分かりませんでした。to_s()メソッドがクラスの文字列表現らしいのですが、うまく出力してくれませんでした。
money.rb
#!/usr/bin/ruby #coding: utf-8 # テスト駆動開発入門10章 興味深い時(times) 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 Franc.new(amount, "CHF") end def self.dollar(amount) return Dollar.new(amount, "USD") end end class Dollar < Money end class Franc < Money end
money_test.rb
#!/usr/bin/ruby #coding: utf-8 # テスト駆動開発入門10章 興味深い時(times) 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.franc(5) == Money.franc(5)) assert(Money.franc(5) != Money.franc(6)) assert(Money.dollar(5) != Money.franc(5)) end def test_Franc_multiplication five = Money.franc(5) assert_equal(Money.franc(10), five * 2) assert_equal(Money.franc(15), five * 3) end def test_currency assert_equal("USD", Money.dollar(1).currency) assert_equal("CHF", Money.franc(1).currency) end def test_different_class_equarity assert(Money.new(10, "CHF") == Franc.new(10, "CHF") ) end end