noizZze

Ruby: Hash#fetch and More

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:

1
2
3
4
5
6
7
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:

1
2
3
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!