-
Notifications
You must be signed in to change notification settings - Fork 5.5k
[WIP] Add safe dig #14203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
[WIP] Add safe dig #14203
Conversation
This comment has been minimized.
This comment has been minimized.
Is it so common? |
Maybe it makes sense to implement dig on the object level..
|
A better name could be [1] pry(main)> "foo".try(:length)
=> 3
[2] pry(main)> "foo".try(:bar)
=> nil
[3] pry(main)> nil.try(:length)
=> nil [1] pry(main)> "foo"&.length
=> 3
[2] pry(main)> "foo"&.bar
NoMethodError: undefined method `bar' for an instance of String (NoMethodError)
"foo"&.bar
^^^^^
from (pry):2:in `__pry__'
[3] pry(main)> nil&.length
=> nil |
Thanks for the suggestion @rnestler! I have opened a feature request regarding this functionality: |
Navigating deeply nested hashes in Ruby can be cumbersome, especially when working with unpredictable API responses or other external data sources.
When accessing data, you may only want the result if you can traverse the entire path without encountering intermediate errors. Many APIs return inconsistent structures, sometimes nested hashes and sometimes plain strings or other types, which makes this process error prone.
The built in
dig
method does not handle mixed types gracefully:A safer approach would be a method that performs these checks internally and stops when it cannot dig further, returning
nil
instead of raising an error.safe_dig overview
safe_dig
traverses a path through nested structures and returnsnil
as soon as it cannot continue. It never raises an error when an intermediate value is not a hash or an array, and it does not require the receiver to implementdig
.Examples
Proper structure
Improper structure with mixed types
Arrays in the path
String and symbol keys
Non container mid path
View specs for more details