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
Written by Pranas Kiziela
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#