wasipeer
wasipeer

Reputation: 1035

Get nested values from a hash using single string

I have a string that represents a sequence of keys in a nested hash in the following format:

keys = 'key1[key2]'

and a nested hash that has the corresponding keys like the following:

hash = {key1: {key2: 'value'}}

Is there any way to get the value from this hash directly as in the following?

value = hash[keys]

Or, do I have to write my own logic?

Upvotes: 0

Views: 45

Answers (2)

ndnenkov
ndnenkov

Reputation: 36101

hash.dig(*keys.delete(']').split('[').map(&:to_sym))

Upvotes: 3

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

To answer your specific question, No, there is no way (to my knowledge) to get the value from hash directly by passing your input string.

You will have to write your own logic to extract the keys from string and then fetch the value.

Upvotes: 0

Related Questions