--1926193751-1885213783-12319842227078 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1885213783-1231984222=:27078" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1885213783-12319842227078 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Thu, 15 Jan 2009, Tom Cloyd wrote: > I'm studying the yield statement for the first time, today. > > All's well until I see this example: > > def myeach(myarray) > iter = 0 > while (iter < myarray.length): > yield(myarray[iter]) > iter += 1 > end > end > > testarray = [1,2,3,4,5] > myeach(testarray) {|item| print "#{item}:"} > 1:2:3:4:5: > > I see a method with one parameter. There a block to the right of the method > call, inexplicably. It would make sense if some iteration were going on, but > I don't see that at all. One call, one execution (with a loop), and we're > out. What does "item" have to count through? > > How can that yield do anything? How does it know about the block? It's not > passed in. The iteration appears to be happening IN the method, using a block > it cannot possibly see. Ouch! After some minutes, I'm not getting this at > all. > > Can anyone clear my head for me. I've never seen anything like this. Or is it > just a weird Ruby idiom I'll just have to accept? I don't think it's weird, and I'd encourage you not to feel glum about having to accept it. It's actually very elegant and cool. The block, like the argument list, is a syntactic construct, part of the method call. It is not, however, an argument; as you say, it is not passed in (though you can "capture" it in a variable if needed). It represents an anonymous function that is being made available for execution, via yield, to the method. When you say the method can't possibly see the block, you're assuming that in a state of nature, methods can receive arguments but can't see code blocks :-) Of course none of it happens except because of how it's engineered, and the code block is part of the engineering, just like the argument list. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management! --1926193751-1885213783-12319842227078-- --1926193751-1885213783-12319842227078--