The Rails I18n library transforms a YAML file into a data structure that is accessible via a dotted path call using the t() function.
t('one.two.three.four')
Does anyone know how to do this with a Ruby Hash? Or is it only possible directly via a YAML object?
This code not only allows dot notation to traverse a Hash but also square brackets to traverse Arrays with indices. It also avoids recursion for efficiency.
Example:
I would suggest taking a look at this gist:
https://gist.github.com/potatosalad/760726
It adds
implode
andexplode
methods toHash
object that transforms nested keys to single-level dotted path keys, and vice versa.Yeah, I don't think that's built-in, anywhere else. But I use something like this in one of my projects:
And then call it like
There is also HashDot.
HashDot allows dot notation syntax use on hashes. It is faster, and more traversable than an object created with OpenStruct.
Just split on a dot in the path and iterate over this to find the right hash?
Alternatively you can build a new hash by iterating recursively over the whole structure:
Ruby 2.3 introduces the
dig
method that looks into nested arrays/hashes, it returnsnil
when no data is found.For example:
Of course if your nested use string keys, the to_sym step is not needed.