GetoptLong#to_hash

I find myself converting the results of option parsing into a hash. I
was wondering if other people would find something like this useful in
the main library:

class GetoptLong
def to_hash
hash = {}
each { |key, val| hash[key] = val or true }
hash
end
end

···


Paul Duncan pabs@pablotron.org pabs in #gah (OPN IRC)
http://www.pablotron.org/ OpenPGP Key ID: 0x82C29562

I used a similar approach, too, and found it very useful. Otherwise I
had to use GetoptLong#each to process all of the options at once,
storing more or less the same information in instance variables for
later use.

I also added an optional parameter to be able to specify default
values. In your code it could look something like:

class GetoptLong
def to_hash( hash = {} )
each { |key, val| hash[key] = val or true }
hash
end
end

so you could call it as

GetoptLong.new( … ).to_hash( “–width” => 35, “–height” => 20 )

Regards,
Pit

···

On 1 Aug 2002, at 15:41, Paul Duncan wrote:

I find myself converting the results of option parsing into a hash. I
was wondering if other people would find something like this useful in
the main library:

class GetoptLong
def to_hash
hash = {}
each { |key, val| hash[key] = val or true }
hash
end
end