Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- t('one.two.three.four')
- path.split(".").inject(hash) { |hash, key| hash[key] }
- def convert_hash(hash, path = "")
- hash.each_with_object({}) do |(k, v), ret|
- key = path + k
- if v.is_a? Hash
- ret.merge! convert_hash(v, key + ".")
- else
- ret[key] = v
- end
- end
- end
- class Hash
- def dig(dotted_path)
- parts = dotted_path.split '.', 2
- match = self[parts[0]]
- if !parts[1] or match.nil?
- return match
- else
- return match.dig(parts[1])
- end
- end
- end
- my_hash = {'a' => {'b' => 'a-b', 'c' => 'a-c', 'd' => {'e' => 'a-d-e'}}, 'f' => 'f'}
- my_hash.dig('a.d.e') # outputs 'a-d-e' (by calling my_hash['a']['d']['e'])
Add Comment
Please, Sign In to add comment