Take the 2-minute tour ×

I find myself needing to put guards like this:

if hash[:foo] && hash[:foo][:bar] && hash[:foo][:bar][:baz] 
    puts hash[:foo][:bar][:baz]

I'd like to shorten this in some way; I know I can wrap in a begin/rescue block but that seems worse. Maybe something like: ruby Hash include another hash, deep check

share|improve this question
duplicated: stackoverflow.com/questions/5429790, and many, many more. –  tokland Nov 14 '11 at 17:45
add comment

2 Answers

up vote 2 down vote accepted

Something like:

def follow_hash(hash, path)
  path.inject(hash) { |accum, el| accum && accum[el] }

value = follow_hash(hash, [:foo, :bar, :baz])
puts value if value
share|improve this answer
I like that. padding. –  Dave Newton Nov 14 '11 at 17:20
add comment

I found this article very informative: http://avdi.org/devblog/2011/06/28/do-or-do-not-there-is-no-try/

value = Maybe(params)[:foo][:bar][:baz][:buz] 
share|improve this answer
add comment

Your Answer


