Project

General

Profile

Actions

Feature #20815

closed

Fetch for nested hash

Added by dmytrostrukov (Dmytro Strukov) about 2 months ago. Updated about 2 months ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:119614]

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 single fetch_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


Related issues 1 (1 open0 closed)

Is duplicate of Ruby master - Feature #12282: Hash#dig! for repeated applications of Hash#fetchOpenActions

Updated by matheusrich (Matheus Richard) about 2 months ago

I think this might have been suggested in the past as deep_fetch. Could it be dig! maybe?

Actions #2

Updated by alanwu (Alan Wu) about 2 months ago

  • Is duplicate of Feature #12282: Hash#dig! for repeated applications of Hash#fetch added

Updated by nobu (Nobuyoshi Nakada) about 2 months ago

data => user: {profile: {name:}}
p name #=> "Alice"

data => user: {profile: {age:}} #=> NoMatchingPatternKeyError

Updated by byroot (Jean Boussier) about 2 months ago

  • Status changed from Open to Closed

Closing because it's a duplicate.

Actions

Also available in: Atom PDF

Like1
Like0Like0Like1Like0