&tag(Ruby/ブロック);
# 普通のブロック
3.times do
puts "hello1"
end
puts ""
# ブロックの中でProcを呼び出す
proc = Proc.new {puts "hello2"}
3.times do
proc.call
end
puts ""
# Procに&をつけて渡すとブロックとして扱われる
3.times(&proc)
# メソッドの仮引数に&をつけるとブロックをProcオブジェクトとして扱える
def sample(&block)
block.call('abc', 'def')
end
sample do |a, b|
puts "#{a} #{b}"
end