rubyの&修飾子について質問があります。
わたしの理解では、プロックをブロックに、ブロックをプロックにする役割だと理解しています。
いま、ブロック内でのreturn、next、returnの動きについて整理しているのですが
ちょっと納得行かないことがあったので相談したいです。
パターン2、3は&修飾子でブロックに変換しているのでパターン1と同じ挙動になると
思っていたのですが、どうやら違うようでした。
なぜでしょうか?
更に、パターン2とパターン3でもそれぞれ挙動が異なります。
Proc、lambdaで作成したオブジェクトはそれぞれ、異なることは理解していますが
&修飾子で変換すると同じブロックになると思っていました。。。
パターン1
ruby
1def enclosing_method 2 x = yield 3 x + 5 4end 5 6def break_sample 7 z = enclosing_method{break 1 + 3} 8 z + 9 9end 10 11def next_sample 12 z = enclosing_method{next 1 + 3} 13 z + 9 14end 15 16def return_sample 17 z = enclosing_method{return 1 + 3} 18 z + 9 19end 20 21puts break_sample #=>13 22puts next_sample #=>18 23puts return_sample #=>4
パターン2
ruby
1def enclosing_method 2 x = yield 3 x + 5 4end 5 6def break_sample 7 z = enclosing_method(&Proc.new{break 1 + 3}) 8 z + 9 9end 10 11def next_sample 12 z = enclosing_method(&Proc.new{next 1 + 3}) 13 z + 9 14end 15 16def return_sample 17 z = enclosing_method(&Proc.new{return 1 + 3}) 18 z + 9 19end 20 21puts break_sample #=> LocalJumpError 22puts next_sample #=> 18 23puts return_sample #=> 4
パターン3
ruby
1def enclosing_method 2 x = yield 3 x + 5 4end 5 6def break_sample 7 z = enclosing_method(&lambda{break 1 + 3}) 8 z + 9 9end 10 11def next_sample 12 z = enclosing_method(&lambda{next 1 + 3}) 13 z + 9 14end 15 16def return_sample 17 z = enclosing_method(&lambda{return 1 + 3}) 18 z + 9 19end 20 21puts break_sample #=>18 22puts next_sample #=>18 23puts return_sample #=>18
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。