加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby使用数组tvalues来索引哈希的嵌套哈希

发布时间:2020-12-16 19:34:25 所属栏目:百科 来源:网络整理
导读:参见英文答案 What is the most ruby-ish way of accessing nested hash values at arbitrary depths? 4个 How to avoid NoMethodError for missing elements in nested hashes,without repeated nil checks?16个 在Ruby中,我想做这样的事情, 我有一个像这样
参见英文答案 > What is the most ruby-ish way of accessing nested hash values at arbitrary depths? 4个
> How to avoid NoMethodError for missing elements in nested hashes,without repeated nil checks?16个
在Ruby中,我想做这样的事情,

我有一个像这样构建的哈希哈希.

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

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

a = [1,2,3]

我想有一个方法,它将使用数组值索引我的哈希中的嵌套键,并返回最后一个键指向的值(由前面的数组/键指导)
例如.

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

如果a = [‘a’,’b’,’c’]则返回值应为basd.

怎么做到这一点?

解决方法

然后是:
keys.inject(hash,:fetch)

或者早期的Ruby版本:

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

如果你确实想要使用递归,那么更多的Rubyesque方法将是:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读