binarymason binarymason - 3 months ago 8
JSON Question

How to recursively send a nested hash the :[] method for any amount of levels?

Context:



What I'm trying to do is make an
Rspec
shared_example called something like
update response
that checks a rails json response of an object and verifies that certain attributes are updated. The json response may or may not have nested attributes. The keys cannot be known ahead of time.

Example:



Say I have a hash,
hsh = {one_deep: 123, nested: {a: 1, b: 2}}
:

I can dynamically send the hash a key if it's one level deep.

def get_value(some_key)
hsh.send(:[], some_key)
end

get_value(:one_deep) # => 123


I can access a nested hash if I hard code the method chain:

def get_value(some_key, another_key)
hsh.send(:[], some_key).send(:[], another_key)
end

get_value(:nested, :a) # => 1
get_value(:nested, :b) # => 2


Desired Endstate:



# The hash key could be 'n' levels deep
#
# This doesn't work... maybe use recursion somehow?
def get_value(*some_keys)
some_keys.each do |key|
hsh.send(:[], key)
end
end


get_value(:nested, :a) # => should output 1
get_value(:nested, :b) # => should output 2

Answer

If you are using, Ruby 2.3.1, then you can use #dig method to fetch the value of a key from nested Hash.

Comments