ruby-on-railsrubyhash-of-hashes

how to make a deep_slice in a hash on ruby


I was looking around for a clean way to do this and I found some workarounds but did not find anything like the slice (some people recommended to use a gem but I think is not needed for this operations, pls correct me if I am wrong), so I found myself with a hash that contains a bunch of hashes and I wanted a way to perform the Slice operation over this hash and get also the key/value pairs from nested hashes, so the question:

Is there something like deep_slice in ruby?

Example:

input: a = {b: 45, c: {d: 55, e: { f: 12}}, g: {z: 90}}, keys = [:b, :f, :z]

expected output: {:b=>45, :f=>12, :z=>90}

Thx in advance! đź‘Ť


Solution

  • After looking around for a while I decided to implement this myself, this is how I fix it:

    a = {b: 45, c: {d: 55, e: { f: 12}}, g: {z: 90}}
    keys = [:b, :f, :z]
    def custom_deep_slice(a:, keys:)
        result = a.slice(*keys)
        a.keys.each do |k|
            if a[k].class == Hash
                result.merge! custom_deep_slice(a: a[k], keys: keys)
            end
        end
        result
    end
    c_deep_slice = custom_deep_slice(a: a, keys: keys)
    p c_deep_slice
    

    The code above is a classic DFS, which takes advantage of the merge! provided by the hash class.

    You can test the code above here