Skip to content

Instantly share code, notes, and snippets.

@aaronpk
Created July 30, 2013 21:31
Show Gist options
  • Select an option

  • Save aaronpk/6117186 to your computer and use it in GitHub Desktop.

Select an option

Save aaronpk/6117186 to your computer and use it in GitHub Desktop.
class NilClass
def [](key)
nil
end
end
payload = nil
puts payload['pull_request']['base']['ref'].inspect
$ ruby test.rb
nil
@kenichi

kenichi commented Jul 30, 2013

Copy link
Copy Markdown

this might better suit your needs:

class Hash

  def deep_fetch *args
    k = args.shift
    key?(k) ? (self[k].respond_to?(:deep_fetch) ? self[k].deep_fetch(*args) : self[k]) : nil
  end

end
>> h = { foo: { bar: { baz: 42}, bat: { baz: 43} }}
=> {:foo=>{:bar=>{:baz=>42}, :bat=>{:baz=>43}}}
>> h.deep_fetch :foo, :bar, :baz
=> 42
>> h.deep_fetch :foo, :bart, :baz
=> nil
>> h.deep_fetch :foo, :bat, :baz
=> 43
>> h.deep_fetch :foot, :bat, :baz
=> nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment