From: 7stud -- Date: 2012-11-06T03:33:00+09:00 Subject: Re: Yield question Assaf Shomer wrote in post #1082905: > Ruby beginner here. > I noticed the following code in the pickaxe book 1.9 page 101: > --------------------- > class VowelFinder > include Enumerable > def initialize(string) > @string = string > end > def each > @string.scan(/[aeiou]/) do |vowel| > yield vowel > end > end > end > -------------------- > What does it mean to have a *yield* inside a block? > 'yield' calls a block. Which block? yield always calls the block that was specified when calling 'the method'. Which method? The method that contains the yield statement. So, work your way outwards from the yield statement until you find a def statement. That is 'the method' whose block(which is specified when calling the method) will be called by yield. > Here the only yield is inside a block > and there is no other method. If yield wasn't allowed inside a block(e.g. a loop), which is inside a method, then you would have to write methods like this: def do_stuff yield 0 yield 1 #... #... yield 998 yield 999 end do_stuff {|x| puts x} --output:-- 1 2 998 999 But of course it makes sense to be able to do this: def do_stuff 1_000.times {|i| yield i} end do_stuff {|x| puts x} --output:-- 0 1 ... ... 998 999 -- Posted via http://www.ruby-forum.com/.