This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: I love open classes
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
Annoyed with the fact that Getoptlong (and every other command line option parser) sucks, I began to consider a rewrite. First step? Make it a subclass of Hash and override methods as needed, instead of the idiotic facade it uses now.
Then I remembered a conversation with Michael Granger about 3 years ago where he mentioned that using a Hash was problematic, because sometimes you need to pass identical options with different values, e.g. "-I" for compiler includes. Don't ask me why I remember that when I can't ever remember what I had for dinner yesterday.
Anyway, simple enough, I'll alter Hash in such a way that instead of overwriting existing key values, it will turn them into an array and store the array as the value for that key. There are a couple of Perl modules that do this, so I took a look at them for inspiration. Here's the Ruby version:
class Hash
alias :old_assign :[]=
def []=(key, val)
if has_key?(key)
orig_val = fetch(key).to_a
old_assign(key, orig_val << val)
else
old_assign(key, val)
end
end
end
# Example usage:
h = {}
h["foo"] = "hello"
h["bar"] = "world"
h["foo"] = "again"
p h["foo"] # ["hello", "again"]
p h["bar"] # "world"