Ruby Hash - Fetch - Returning a (Default) Value for a Key That Does Not Exist


Programming in Ruby tutorials and examples

Ruby Hash - Fetch - Returning a (Default) Value for a Key That Does Not Exist

MaxCDN Content Delivery Network

I was looking at some ruby code I wrote a few days ago and something didn’t sit right with me. I had a bit of a code smell when setting a default value for a hash key if the key didn’t exist.

The scenario… there is a hash that has a search key which holds information for a search term, optionally the order key may be set also.

1
  hash = {:search => "ruby hashes" }

Initially when the order key had not been set I would perform a check to see if they key existed then using the ternary operator set a default value. I think it looks a bit ugly though!

1
  order = hash.key?(:order) ? hash[:order] : :desc

How have I not heard of the fetch method before? Fetch takes a key argument which will be used to look up the key in the hash, optionally it takes a second parameter which is the value to return if the key has not been set.

1
  order = hash.fetch(:order, :desc)

A small refactor which I think looks much nicer. This may be obvious to some, but it was one of those methods I had just never used!

Comments