A cute little trick with Ruby hashes and .try()

Recently I encountered a situation where incoming JSON was converted to a hash, and certain keys were not always present. Naturally I want to safely grab the values that were present without barfing on the nils.

    
    hsh = {foo: bar: [2]}
    bad_hsh = {foo: nil}
    should_be_2 = hsh[:foo][:bar].first # works
    uhoh = fail[:foo][:bar].first # NilClass error

At first began looking for a way to use .try() to get at nested hash values (since we’re not on Ruby 2.3 yet and can’t use the lonely operator). But the normal try syntax didn’t work:

    uhoh = fail[:foo].try([:bar]).try(:first) # does not work

But then I remembered that [] is actually the name of the method, and what’s in it is the first parameter, so I tried this:

    win = fail[:foo].try([], :bar).try(:first) # It works!

This is not fantastic code, I know there are better ways to do this, and I can’t wait to upgrade to Ruby 2.3, but I do find this interesting.