Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Ruby Hash Using Dotted Path Key String

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?

like image 259
matsko Avatar asked Aug 21 '11 16:08

matsko


1 Answers

Just split on a dot in the path and iterate over this to find the right hash?

path.split(".").inject(hash) { |hash, key| hash[key] }

Alternatively you can build a new hash by iterating recursively over the whole structure:

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
like image 68
Mon ouïe Avatar answered Oct 14 '22 19:10

Mon ouïe