hakeの日記

Windows環境でプログラミングの勉強をしています。

Kernel#block_given?

Rubyの勉強
WEBrickのサンプルで出てきた記述。メソッドでブロック付きと無しで違う動作が定義できるみたいです。

class Test
  def initialize
    @array = ['a', 'b', 'c', 'd']
  end
  def test
    if block_given?
      @array.each do |i|
        yield i + ":"
      end
    else
      @array
    end
  end
end

a = Test.new
a.test{|i| print i}  # => a:b:c:d:
p a.test             # => ["a", "b", "c", "d"]