Last Updated: February 25, 2016
·
420
· pranas

Use Hash#fetch over Hash#[]

Few advantages:

1) Easier debugging

You get KeyError exception immediately when you try to access hash value that was not set instead of passing nil further to your code and debugging "undefined method X for nil:NilClass"

2) Let's you specify default value

h.fetch("username", "guest")
#=> "guest"
h.fetch("username") { |key| "#{key} is not set"}
#=> "username is not set"

Based on article from 8th Light