Sometimes you rediscover little features that make your life whole lot easier. Today when reviewing the code of my co-worker I stumbled upon the use of the “fetch” on the Hash object. Check it:

h = { :existing_key => "value" }

h.fetch(:existing_key)                  # returns "value"

h.fetch(:some_key)                      # raises exception
h.fetch(:some_key, "default")           # returns "default"
h.fetch(:some_key) { ...some math... }  # returns some math

One other related technique is:

h[:existing_key]                        # returns "value"
h[:some_key]                            # returns nil
h[:some_key] || "default"               # returns "default"

Armed and ready!

P.S. Thanks for a great tip, Craig!