ruby 使用数组 tvalues 来索引哈希的嵌套哈希 [英] ruby use array tvalues to index nested hash of hash

查看:63
本文介绍了ruby 使用数组 tvalues 来索引哈希的嵌套哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,我想做这样的事情,

In Ruby, I want to do something like this,

我有一个像这样构建的散列.

I have a hash of hash built like this.

h = {1 => {2 => {3 => "three"}},'a' => { 'b' => { 'c' => "basd"}}}
=> {"a"=>{"b"=>{"c"=>"basd"}}, 1=>{2=>{3=>"three"}}}

如果我有一个包含这样值的数组.

If I have an array with values like this.

a = [1, 2, 3]

我想要一种方法,该方法将使用数组值来索引散列中的嵌套键并返回最后一个键指向的值(按照之前的数组/键的指导)例如.

I want to have a method which will use the array values to index nested keys in my hash and return the value pointed by last key (as guided by previous array/keys) for eg.

getHashValue([1,2,3]) should return "three" => h[1][2][3]

if a = ['a','b', 'c'] 那么返回值应该是 basd.

if a = ['a','b', 'c'] then the return value should be basd.

如何完成这项工作?

推荐答案

然后是:

keys.inject(hash, :fetch)

或者对于早期的 Ruby 版本:

or for earlier Ruby versions:

keys.inject(hash) {|h, k| h[k]}

如果您确实想使用递归,则更像 Rubyesque 的方法是:

If you did want to use recursion, a more Rubyesque approach would be:

def get_value(obj, keys)
  keys.empty? ? obj : get_value(obj[keys[0]], keys[1..-1])
end

这篇关于ruby 使用数组 tvalues 来索引哈希的嵌套哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆