Skip to content

Instantly share code, notes, and snippets.

@arathunku
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save arathunku/c60f02a5c64a1a7cb629 to your computer and use it in GitHub Desktop.

Select an option

Save arathunku/c60f02a5c64a1a7cb629 to your computer and use it in GitHub Desktop.
def fetch(hash, *keys, &block)
index = 0
keys.reduce(hash) do |coll, key|
index += 1
v = coll[key]
if v
v
else
if !block.nil? && index == keys.size
block.call
else
coll.fetch(key)
end
end
end
end
fetch({a: {}}, :b)# exception for missing b
fetch({a: {}}, :a) # {}
fetch({a: {}}, :b) { "default"} # default
fetch({a: {}}, :b, :c) { "default"} # exception for missing b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment