From: Florian Frank Date: 2007-10-11T18:34:21+09:00 Subject: Re: Why does this use a block 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. The > constructor simply makes a yield call, passing self as an argument. > > What is the point of this? Can we not convert > > opts = OptionParser.new() {|opts| body} > > To > > opts = OptionParser.new() > body > > ? This seems more natural to me. But the former seems like a common Ruby > idiom so I'm wondering what I am missing. > You might want to use the shortcut option_parser = OptionParser.new do |o| o.foo = "foo" o.bar = "bar" ... end during initialization of the object instead of using the long name, that will be used later in the program after you forgot, what "o" meant. I don't know if this is the case with OptionParser, but many methods also want to do some housekeeping after the execution of the block, for example, open(...) do |f| ... end closes the opened file. A constructor might want to check his configuration (given in the block) and raise an exception, if errors were found. This is better than creating a wrongly configured object, that only will throw an exception later in the program. -- Florian Frank