Some things I have learned about Ruby's fetch method
Here are some things that I have learned about 'fetch' that you may find useful
Recently I have learned a couple of things about Ruby’s fetch method that I would like to share.
The first is a pretty straightforward one, using fetch is preferable to using the [‘key’] notation in times when you want your system to fall over if the key doesn’t exist. Here is an example;
test = {:a => 'test', :b => 'test'}
p test[:a] #=> 'test'
p test.fetch(:a) #=> 'test'
Nothing odd here, but what about;
p test[:c] #=> nil (this could be dangerous)
p test.fetch(:c) #=> `fetch': key not found (IndexError) Much safer if we aren't expecting nil
The next thing I have learned is that if you have the case were you want default values to be added in the case of fetch not working, or indeed you want some better form of logging without the site falling over you can pass a block to fetch;
p test.fetch(:c) { 'Default' } #=> 'Default'
Finally, you can pass a second parameter into fetch that would act as the default value, but this should be avoided because the second parameter is always evaluated, even if it isn’t needed, so if you pass a method in there it is going to be called each time even though the return value may never be used.