This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Hash#fetch
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
There's one immediate problem. What if false is a valid key argument? Or what if you want to merely check if a particular key has been defined even if it's nil? The above code will fail. But Hash#fetch has slightly different semantics. It checks that the key is defined without concern for the actual value and so, can pick up false and nil key values
Basically, you've got three options. Option 1 is to fail with an IndexError if the key isn't defined:
SomeHash.fetch(:bogus) # Boom, IndexError
# vs.
SomeHash[:bogus] # nil
Option 2 lets you specify a default value if the key isn't found:
SomeHash.fetch(:bogus, 7) # 7
Option 3 allows the value of a code block to serve as the value. This is generally used to re-raise a custom exception.
SomeHash.fetch(:bogus){ raise MyError, "Key not found" }