Actions
Feature #20815
closedFetch for nested hash
    Feature #20815:
    Fetch 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_nestedwould 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_nestedmethod 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) about 1 year ago
          Updated by matheusrich (Matheus Richard) about 1 year ago
          
          
        
        
      
      I think this might have been suggested in the past as deep_fetch. Could it be dig! maybe?
        
           Updated by alanwu (Alan Wu) about 1 year ago
          Updated by alanwu (Alan Wu) about 1 year ago
          
          
        
        
      
      - Is duplicate of Feature #12282: Hash#dig! for repeated applications of Hash#fetch added
        
           Updated by nobu (Nobuyoshi Nakada) about 1 year ago
          Updated by nobu (Nobuyoshi Nakada) about 1 year ago
          
          
        
        
      
      data => user: {profile: {name:}}
p name #=> "Alice"
data => user: {profile: {age:}} #=> NoMatchingPatternKeyError
        
           Updated by byroot (Jean Boussier) about 1 year ago
          Updated by byroot (Jean Boussier) about 1 year ago
          
          
        
        
      
      - Status changed from Open to Closed
Closing because it's a duplicate.
Actions