Access Ruby Hash Using Dotted Path Key String

后端 未结 7 2169
情深已故
情深已故 2021-01-01 21:35

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\         


        
7条回答
  •  被撕碎了的回忆
    2021-01-01 22:20

    Ruby 2.3 introduces the dig method that looks into nested arrays/hashes, it returns nil when no data is found.

    For example:

    test_data = {a: {b: {c: {d: 1}, e: 2}}}
    path = 'a.b.c.d'.split('.').map(&:to_sym)
    # path => [:a, :b, :c, :d]
    test_data.dig(*path)
    

    Of course if your nested use string keys, the to_sym step is not needed.

提交回复
热议问题