From: "David A. Black" Date: 2009-01-15T10:54:59+09:00 Subject: Re: yield example baffling - need help --1926193751-778988355-1231984558=:27078 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-778988355-1231984558=: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-778988355-1231984558=:27078 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Thu, 15 Jan 2009, Tom Cloyd wrote: > Tom Cloyd wrote: >> I'm studying the yield statement for the first time, today. >>=20 >> All's well until I see this example: >>=20 >> def myeach(myarray) >> iter =3D 0 >> while (iter < myarray.length): >> yield(myarray[iter]) >> iter +=3D 1 >> end >> end >>=20 >> testarray =3D [1,2,3,4,5] >> myeach(testarray) {|item| print "#{item}:"} >> =E2=86=92 1:2:3:4:5: >>=20 >> I see a method with one parameter. There a block to the right of the met= hod=20 >> call, inexplicably. It would make sense if some iteration were going on,= =20 >> but I don't see that at all. One call, one execution (with a loop), and= =20 >> we're out. What does "item" have to count through? >>=20 >> How can that yield do anything? How does it know about the block? It's n= ot=20 >> passed in. The iteration appears to be happening IN the method, using a= =20 >> block it cannot possibly see. Ouch! After some minutes, I'm not getting= =20 >> this at all. >>=20 >> Can anyone clear my head for me. I've never seen anything like this. Or = is=20 >> it just a weird Ruby idiom I'll just have to accept? >>=20 >> Thanks in advance. >>=20 >> Tom >>=20 >>=20 > Arrgh. What a dolt. I just realized that ALL the yield examples I've been= =20 > studying have this block sitting over to the right - I was converting the= =20 > curly braces to parens in my mind, and so didn't see them. It IS idiomati= c=20 > weirdness. I yield to higher wisdom. Half the fun, actually, is that while you know what you're yielding, you never know exactly what you're yielding *to* :-) The block construct actually has two common use patterns: iterating through collections, and yielding "magic pen" objects.[1] An example of the magic pen is File.open: File.open("blah", "w") do |fh| fh.puts(whatever) end where the open method, which you never have to see, does the housekeeping, including closing the file for you. You just get the magic pen (the file handle). That pattern is, I think, particularly nice. David [1] http://dablog.rubypal.com/2007/2/18/the-magic-pens-of-ruby --=20 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 =3D> Independent, social wishlist management! --1926193751-778988355-1231984558=:27078-- --1926193751-778988355-1231984558=:27078--