0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyのyieldとブロック

Posted at

yieldについて

メソッドに渡されたブロックを実行します。

そもそもブロックって

ブロックとは { ~ } で囲まれた処理や、do ~ endで囲まれた処理のことを指すそうです。
余談ですが、callメソッドで自身の処理を呼び出せます。

proc_obj1 = Proc.new { |arg| p arg }
proc_obj2 = Proc.new do |arg|
  p arg
end
proc_obj1.call('hoge') # hoge
proc_obj2.call('hoge') # hoge 

yieldは引数で渡されたブロックを実行する

def yield_test
  yield( 10, 20 )
end

puts yield_test { |x, y| x + y } # 30
puts yield_test { |x, y| x * y } # 200

puts yield_test { |x, y| x + y } # 30の、{ |x, y| x + y } 部分がブロックで、yield_testではそのブロックに(10,20)という引数をわたして実行しています。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?