Actions
Feature #20815
closedFetch for nested hash
Status:
Closed
Assignee:
-
Target version:
-
Description
I propose adding a fetch_nested
method to Ruby’s Hash class, allowing developers to fetch values deeply nested within a hash, with an error raised if any key in the provided path is missing. The method would be similar to dig, but with the added functionality of error handling when keys are not found, improving code readability and robustness when accessing nested data structures.
Rationale
- Enhanced Error Handling:
fetch_nested
would raise an error if a key in the specified path does not exist, which is critical for cases where the absence of specific keys indicates a data integrity issue or invalid structure. This makes debugging easier and helps catch issues early in the development process. - Improved Code Readability: Without
fetch_nested
, developers often chain multiple fetch calls or rely on error-prone conditional checks, complicating code. A singlefetch_nested
method call would simplify syntax and improve readability when working with deeply nested hashes. - Alignment with Ruby’s Error-First Philosophy: Ruby’s fetch method already offers error handling for missing keys at the top level of a hash. Extending this philosophy to nested hashes would offer consistency and convenience, aligning with Ruby’s emphasis on developer-friendly and expressive error handling.
Example Usage
data = { user: { profile: { name: "Alice" } } }
# Current approach
data.fetch(:user).fetch(:profile).fetch(:name) # Or use dig without error handling
# Proposed `fetch_nested`
data.fetch_nested(:user, :profile, :name) # Raises KeyError if any key is missing
Updated by matheusrich (Matheus Richard) 24 days ago
I think this might have been suggested in the past as deep_fetch
. Could it be dig!
maybe?
Updated by alanwu (Alan Wu) 24 days ago
- Is duplicate of Feature #12282: Hash#dig! for repeated applications of Hash#fetch added
Updated by nobu (Nobuyoshi Nakada) 24 days ago
data => user: {profile: {name:}}
p name #=> "Alice"
data => user: {profile: {age:}} #=> NoMatchingPatternKeyError
Updated by byroot (Jean Boussier) 23 days ago
- Status changed from Open to Closed
Closing because it's a duplicate.
Actions
Like1
Like0Like0Like1Like0