0

I find myself needing to put guards like this:

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

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

Community
  • 1
  • 1
Matt Rogish
  • 24,435
  • 11
  • 76
  • 92

2 Answers2

2

Something like:

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

value = follow_hash(hash, [:foo, :bar, :baz])
puts value if value
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
1

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] 
bheeshmar
  • 3,125
  • 1
  • 19
  • 18