Skip to content
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

Add to_nested_h to arrays #6

Merged
merged 1 commit into from
Dec 18, 2024
Merged

Conversation

Tobias-Knudsen
Copy link
Member

@Tobias-Knudsen Tobias-Knudsen commented Dec 17, 2024

This PR adds a new method, to_nested_h, to the Array class. The method allows converting an array of keys at multiple levels into a nested hash with a specified default value at its leaf nodes. It supports arrays of arbitrary depth and ensures consistent behavior, even for edge cases like empty arrays.

Motivation

Currently, Array#to_h works well for flat key-value pair conversions but doesn't support nested structures. This method addresses that gap, enabling developers to build nested hash structures in a clean and intuitive way.

Given a multi-dimensional array, to_nested_h generates a nested hash where the keys are derived from each level of the array. Leaf nodes in the resulting hash are assigned a default value, which can be customized.

Usage Examples

Single Level

[[:a, :b]].to_nested_h
# => { a: nil, b: nil }

Two Levels

[[:a, :b], [:x, :y]].to_nested_h(value: 0)
# => { a: { x: 0, y: 0 }, b: { x: 0, y: 0 } }

Multiple Levels

[[:a, :b], [:x, :y], [:m, :n]].to_nested_h(value: 'leaf')
# => {
#   a: { x: { m: 'leaf', n: 'leaf' }, y: { m: 'leaf', n: 'leaf' } },
#   b: { x: { m: 'leaf', n: 'leaf' }, y: { m: 'leaf', n: 'leaf' } }
# }

Empty Array

[].to_nested_h
# => {}

@Tobias-Knudsen Tobias-Knudsen merged commit dda0aad into develop Dec 18, 2024
1 check passed
@Tobias-Knudsen Tobias-Knudsen deleted the feature/arr-to-nested-hash branch December 18, 2024 09:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants