Build a hash from ARGV, the Ruby way

T

Toby Rodwell

I would like to build a hash from ARGV using UNIX type notation ie any
argument which begins with a hyphen or double hyphen is an option and
may have as value(s) the argument(s) which succeed it (if they don't
have hyphens). Options without values should result in a hash element
which has a key and a dummy value (say "0").

I suspect/hope there is a very simple "Ruby way" to do this, but I got
stuck thinking how to look ahead when iterating through ARGV. I've got
a bodged method of just taking pairs eg -a 1 -b 0 -c 3 etc, but it would
be nice to it properly. Any suggestions? All help appreciated!
 
I

Intransition

I would like to build a hash from ARGV using UNIX type notation ie any
argument which begins with a hyphen or double hyphen is an option and
may have as value(s) the argument(s) which succeed it (if they don't
have hyphens). =A0Options without values should result in a hash element
which has a key and a dummy value (say "0").

I suspect/hope there is a very simple "Ruby way" to do this, but I got
stuck thinking how to look ahead when iterating through ARGV. =A0I've got
a bodged method of just taking pairs eg -a 1 -b 0 -c 3 etc, but it would
be nice to it properly. =A0Any suggestions? =A0All help appreciated!

$ gem install facets
$ irb
 
B

Brian Candler

Toby said:
I would like to build a hash from ARGV using UNIX type notation ie any
argument which begins with a hyphen or double hyphen is an option and
may have as value(s) the argument(s) which succeed it (if they don't
have hyphens). Options without values should result in a hash element
which has a key and a dummy value (say "0").

Take a look at optparse.rb in the standard ruby library:
http://ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html

Then if you don't like that, there are several other libraries that
other people have written with more "object like" APIs and very
forgettable names. One I came across recently was thor:
http://github.com/wycats/thor
 
W

William Morgan

Reformatted excerpts from Toby Rodwell's message of 2010-01-25:
I suspect/hope there is a very simple "Ruby way" to do this, but I got
stuck thinking how to look ahead when iterating through ARGV. I've
got a bodged method of just taking pairs eg -a 1 -b 0 -c 3 etc, but it
would be nice to it properly. Any suggestions? All help appreciated!

You can start doing something simple with ARGV.each_slice(2), but any
kind of error checking quickly gets complicated. Trollop will do this
exact thing for you (turn ARGV into a hash with error checking).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top