Learn Ruby with Edgecase Ruby Koanをやってみた

Rails Hub情報局: 禅の公案(Koan)がプログラミング学習でプチブーム
こちらで紹介されているLearn Ruby with the EdgeCase Ruby Koansをやってみました。


テストやコードを書きながら、rubyの構文を学べます。
method_missingやblockのコードはためになりました。

補足

テスト実行は面倒なので、ぐるぐる回してやりました。

while true; do ruby path_to_enlightenment.rb;sleep 3;  done

参考になったとこ

ensureの使い方
  def file_sandwich(file_name)
    file = open(file_name)
    yield(file)
  ensure
    file.close if file
  end

  def count_lines2(file_name)
    file_sandwich(file_name) do |file|
      count = 0
      while line = file.gets
        count += 1
      end
      count
    end
  end
block_given?
  def yield_tester
    if block_given?
      yield
    else
      :no_block
    end
  end

  def test_methods_can_see_if_they_have_been_called_with_a_block
    assert_equal :with_block, yield_tester { :with_block }
    assert_equal :no_block, yield_tester
  end
method_missing
  class WellBehavedFooCatcher
    def method_missing(method_name, *args, &block)
      if method_name.to_s[0,3] == "foo"
        "Foo to you too"
      else
        super(method_name, *args, &block)
      end
    end
  end

  def test_foo_method_are_caught
    catcher = WellBehavedFooCatcher.new

    assert_equal 'Foo to you too', catcher.foo_bar
    assert_equal 'Foo to you too', catcher.foo_baz
  end

  def test_non_foo_messages_are_treated_normally
    catcher = WellBehavedFooCatcher.new

    assert_raise(NoMethodError) do
      catcher.normal_undefined_method
    end
  end