MENU

ruby block_given?

挙動確認

メソッドに、{}か do endが渡されていれば block_given?はtrueになる

def check
  if block_given?
    puts "Block is given."
  else
    puts "Block isn't given."
  end
end
check{} #=> Block is given.
check #=> Block isn't given.

サンプル

渡されたブロックは、yieldで実行されている

def block_test
  5.times {yield()}
end

block_test{
  puts "ブロック本体"
}
  • blockに引数を使う
def block_test(word)
  5.times {yield(word)}
end

block_test("ブロック本体"){ |word|
  puts word
}

=> ブロック本体 が5

参考記事

qiita.com

docs.ruby-lang.org