From: Rick DeNatale Date: 2007-10-11T21:56:10+09:00 Subject: Re: Why does this use a block On 10/11/07, Robert Klemme wrote: > 2007/10/11, Eric Hodel : > > On Oct 11, 2007, at 24:12 , Anonymous wrote: > > > So I'm new to Ruby and I'm trying to use OptionParser to parse in some > > > command line arguments. I looked at some documentation on > > > OptionParser and there is something that's confusing me to no end. > > > In all the examples a block is being passed in to the constructor > > > of the OptionParser object. > > It works both ways. Blocks are pretty, so people use them. > > There are in fact important differences to both approaches. First, > OptionParser's #initialize is free to yield whatever it decides to the > block. So you are not guaranteed to receive the new OptionParser > instance. This is important to keep in mind because the > implementation might change at a later point so the lib could yield a > different instance which should, of course, support the documented > interface. > > Second, with the block form OptionParser#initialize is able to detect > when the user initialization has finished and can do finalizing work. > It could, for example, invoke #freeze to make sure the configuration > is not changed any more. Or it can verify that client code properly > initialized it (avoiding duplicate or ambiguous option settings for > example). I'm pretty sure that I've seen a variant on this in which initialize evaluates the block with instance_eval rather than yield or call. This allows the block to invoke private methods during initialization. IIRC the Ruby tk bindings so this. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/