# OptionParser questions

**URL:** <https://www.ruby-forum.com/t/optionparser-questions/71166>\
**Category:** Ruby\
**Created:** [October 5, 2006, 9:05pm UTC](https://www.ruby-forum.com/t/optionparser-questions/71166 "2006-10-05T21:05:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![iceburgh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/c4cdca/32.png) [@iceburgh](https://www.ruby-forum.com/u/iceburgh)\
**Post date:** [October 5, 2006, 9:05pm UTC](https://www.ruby-forum.com/t/optionparser-questions/71166/1 "2006-10-05T21:05:31Z")

</div>

I’m a bit confused by the way that OptionParser works. In  
the “Complete example” on

[http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html](http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html)

I see

opts = OptionParser.new do |opts|  
opts.banner = “Usage: example.rb [options]”  
…

It looks like the “opts” object is being handed to the block,  
as well as being returned as the result of the “new” method.  
Is this the case? Is this a common way of doing things? Are  
there any caveats that must be observed in this situation?

## -r

[http://www.cfcl.com/rdm](http://www.cfcl.com/rdm) Rich M.  
[http://www.cfcl.com/rdm/resume](http://www.cfcl.com/rdm/resume) removed\_email\_address@domain.invalid  
[http://www.cfcl.com/rdm/weblog](http://www.cfcl.com/rdm/weblog) +1 650-873-7841

Technical editing and writing, programming, and web development

---

<div class="post-metadata">

**Author:** ![iceburgh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/c4cdca/32.png) [@iceburgh](https://www.ruby-forum.com/u/iceburgh)\
**Post date:** [October 5, 2006, 9:37pm UTC](https://www.ruby-forum.com/t/optionparser-questions/71166/2 "2006-10-05T21:37:37Z")

</div>

Le 5 octobre 2006 à 21:03, Rich M. a écrit :

> opts = OptionParser.new do |opts|  
> opts.banner = “Usage: example.rb [options]”  
> …
> 
> It looks like the “opts” object is being handed to the block,  
> as well as being returned as the result of the “new” method.  
> Is this the case?

Not really. I’d say that example is badly written. The  
OptionParser.new call can take a block, with one parameter. The name  
between || is the name of that parameter, and is a variable local to the  
block. I’d write something like this myself :

opts = OptionParser.new do |o|  
o.banner = …  
…  
end

(If the whole code is inside the block, you can even drop the first  
assignment, too.)

> Is this a common way of doing things? Are  
> there any caveats that must be observed in this situation?

I’m not good enough with the Ruby usages to reply here…

Fred
