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

Get leaf_keys from any hash #3

Open
Tobias-Knudsen opened this issue Dec 17, 2024 · 0 comments
Open

Get leaf_keys from any hash #3

Tobias-Knudsen opened this issue Dec 17, 2024 · 0 comments

Comments

@Tobias-Knudsen
Copy link
Member

Tobias-Knudsen commented Dec 17, 2024

Example Usage:

nested_hash = {
  a: {
    x: 1,
    y: { z: 2 }
  },
  b: {
    m: { n: 3, o: 4 },
    p: 5
  },
  c: 6
}

result = leaf_keys(nested_hash)
puts result => [:x, :z, :n, :o, :p, :c]

We might want to get the set of unique leaf keys back by default

Suggested solution

def leaf_keys
  each_with_object([]) do |(key, value), result|
    if value.is_a?(Hash) && !value.empty?
      result.concat(value.leaf_keys)
    else
      result << key
    end
  end.uniq
end
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

No branches or pull requests

1 participant