Skip to content

Instantly share code, notes, and snippets.

@labocho
Last active August 17, 2021 06:11
Show Gist options
  • Save labocho/baba65d2effc0e7711abd8e415679c91 to your computer and use it in GitHub Desktop.
Save labocho/baba65d2effc0e7711abd8e415679c91 to your computer and use it in GitHub Desktop.
Change Hash or Array's `[]` to `fetch` recursively
# Usage:
# h = StrictAccessor.strictify({a: 1, b: [{c: 3}]})
# h[:c] # KeyError
# h[:b][1] # IndexError
module StrictAccessor
def self.strictify(object)
case object
when Array
object.map {|e| strictify(e) }.extend(self)
when Hash
object.each_with_object({}) {|(k, v), h| h[k] = strictify(v) }.extend(self)
else
object
end
end
def [](key_or_index)
fetch(key_or_index)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment