binarymason binarymason - 1 year ago 78
JSON Question

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


What I'm trying to do is make an
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.


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)

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)

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)

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download