How do I use the fetch method for nested hash?

后端 未结 7 1334
后悔当初
后悔当初 2021-02-19 14:45

I have the following hash:

hash = {\'name\' => { \'Mike\' => { \'age\' => 10, \'gender\' => \'m\' } } }

I can access the age by:

7条回答
  •  青春惊慌失措
    2021-02-19 15:30

    A version that uses a method instead of adding to the Hash class for others using Ruby 2.2 or lower.

    def dig(dict, *args)
      key = args.shift
      if args.empty?
        return dict[key]
      else
        dig(dict[key], *args)
      end
    end
    

    And so you can do:

    data = { a: 1, b: {c: 2}}
    dig(data, :a) == 1
    dig(data, :b, :c) == 2
    

提交回复
热议问题