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
  • 23,729
  • 11
  • 74
  • 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
  • 64,361
  • 11
  • 127
  • 168
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,025
  • 1
  • 17
  • 18