2 October 2014
#fetch method in Ruby is implemented in both the
Hash classes, and offers very similar results to the
The difference lies in how they handle missing keys:
# method returns
nil (usually, see footnote),
#fetch will raise an exception. The method also accepts a second parameter or block, which is called only in the event of the key not being found. This could be used to raise a more informative error, or return an alternative value.
Lastly, I’ve found
#fetch useful for when a falsey value would be valid, and you need to distinguish between them and missing keys.
To get around this, we can use
#fetch to set the Logger if the key is not present.
In the end, it comes down to whether or not you need
false to act the same as a missing key. If you don’t, use
* When calling
# with a missing key, the
#default_proc is called if it is set, or the value of
#default is returned (which by default, is
nil). See Hash#default for more details.