From: David Alan Black Date: 2001-12-31T11:06:39+09:00 Subject: [ruby-talk:29782] Re: Proc.class vs yield Hello -- On Mon, 31 Dec 2001, Michael Lucas-Smith wrote: > Hi, > I'm a Smalltalk programmer and I have to say, of what I've seen of > Ruby Welcome to Ruby! > I'm impressed. I like it. Except for one inconsistency which really > drives me up the wall. Two objects that nearly do the same thing, Proc > and Block? { someCode } - one you send yield to, the other you send call. > > Why?! That means you have to know what kind of object you have before > you can send the message to it. Well, the only time you would use yield is in an iterator, when you want to yield control to the block associated with the method call (and get back the result). You don't exactly send yield to the block; that is, yield is not a method. You'd want to send "call" to a Proc object. Normally there shouldn't be any ambiguity about this. If you've got a reference to something in a variable, it's a Proc. You can convert a block to a Proc with "proc" (aka "lambda"). Also, when a block is supplied to a method, you can capture that block, converted to a Proc object, with the &var syntax in the param list. You can then call that Proc: def some_iterator(&b) # b now refers to the given block # Call it five times: 5.times {|i| b.call(i) } end some_iterator {|i| puts i} The more usual way to do it would be: def some_iterator 5.times {|i| yield i} end that is, just letting control bounce back and forth, courtesy of yield. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav