Last active
August 17, 2021 06:11
-
-
Save labocho/baba65d2effc0e7711abd8e415679c91 to your computer and use it in GitHub Desktop.
Change Hash or Array's `[]` to `fetch` recursively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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