Ruby Tips!

RubyのTipsを紹介します

ブロックの受け取りと受け渡し

ブロックを受け取るメソッドは、仮引数に&を付けておくとブロックをProcオブジェクトとして受け取れるようになる。

def method_with_block(&blk)
  p blk #=> Proc
end

またProcオブジェクトは、実引数に&を付けてメソッドに渡せば、ブロックとして受け渡すことができるようになっている。

proc = Proc.new{|i|
  puts i
}
10.times(&proc) # 0 .. 9

これら2つの事を組み合わせると、ブロックを受け取り、それをそのまま別のメソッドに受け渡すことで、処理を別のメソッドに完全に移譲することも可能になる。

def delegate_method(&blk)
  target_method(&blk) # target_methodに処理を移譲
end

def target_method
  yield
end

delegate_method{
  puts "Hello, World!"
}