The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
I love open classes

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Daniel Berger

Posts: 1383
Nickname: djberg96
Registered: Sep, 2004

Daniel Berger is a Ruby Programmer who also dabbles in C and Perl
I love open classes Posted: Jul 22, 2005 3:03 PM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Daniel Berger
Latest Posts From Testing 1,2,3...

Advertisement
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"

Read: I love open classes

Topic: Tagging self reference Previous Topic   Next Topic Topic: Thread.new(info)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use