The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hash#fetch

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
Hash#fetch Posted: Aug 5, 2009 5:16 PM
Reply to this message Reply

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

Advertisement
I generally eschew Array#fetch. It's worthless in my opinion. But what about Hash#fetch? Ah, now there's a good reason for this one. Consider this:
def foo(name)
   code = SomeHash[name]
   raise ArgumentError, "Illegal prototype '#{name}'" unless code
   return code
end

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

Read: Hash#fetch

Topic: imap_processor 1.3 Previous Topic   Next Topic Topic: A faster Ruby on Windows is possible (benchmarks for 4 implementations inside)

Sponsored Links



Google
  Web Artima.com   

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