LoginSignup
5

More than 5 years have passed since last update.

Rubyにおけるyieldの意味

Posted at

yieldの意味がしばらくわからなかったけど、いろいろなサイトを見つけながら感覚を掴んだので、書く。

yield とは

yieldはあるメソッドに渡された手続きを実行するためのシンボル。

例えば

とあるメソッドを用意して、その中でyieldを宣言する。

def some_method(x)
  yield x
end

このメソッドに対して、{|i| puts i}という手続きAを渡してやると、yieldが宣言された箇所で手続きAが実行される。
こんな感じ。

some_method('hoge'){|i| puts i}

すると実行結果は、以下のようになる。

=> hoge

some_methodは何もやらないメソッドなのに渡した手続きが実行されて、hogeが出力されます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5