0

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?

3
  • 3
    You have to write a piece of your own logic to handle this. Commented Oct 31, 2018 at 7:54
  • 1
    Can you give an example for 3-level nesting? Will it be 'key1[key2][key3]' or 'key1[key2[key3]]'? Commented Oct 31, 2018 at 8:06
  • key1[key2][key3] Commented Oct 31, 2018 at 9:24

2 Answers 2

3
hash.dig(*keys.delete(']').split('[').map(&:to_sym))
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.