【问题标题】:How to use a key path to traverse a hash map in Ruby?如何使用关键路径遍历 Ruby 中的哈希映射?
【发布时间】:2021-10-24 19:09:12
【问题描述】:

所以我有一个嵌套哈希,如下所示:

nested_hash = {
  foo: foo,
  bar: {
    foo: foo,
    bar: {
      foo: foo,
      bar: {
        foo: bar
      }
    }
  }
}

要访问不同级别的值,您可以使用多种方法,如下所示:

def one_level(key1)
  nested_hash[key1]
end

def two_levels(key1, key2)
  nested_hash[key1][key2]
end

def three_levels(key1, key2, key3)
  nested_hash[key1][key2][key3]
end

但也许您需要像这样的一种方法:

def up_to_three_levels(key1, key2, key3)
  if key1 && key2 && key3
    nested_hash[key1][key2][key3]
  elif key1 && key2
    nested_hash[key1][key2]
  else
    nested_hash[key1]
  end
end

这显然不理想,也无法扩展。如果我可以传递任意长度的数组以达到任意级别,那就太好了。有没有这样的方法?

(对于上下文:我要解决的问题是我需要将键路径作为参数并使用它从多个不同的数据结构中获取数据。)

【问题讨论】:

    标签: arrays ruby nested hashmap keypaths


    【解决方案1】:

    是的。它叫dig

    nested_hash.dig(key1, key2, key3)
    

    它不需要数组,但有一个 splat 运算符 (*) 可让您将数组转换为参数列表,如下所示:

    nested_hash.dig(*[key1, key2, key3])
    

    并不是说你必须自己实现它,但我认为知道这是一个非常简单的递归问题,只需几行代码就可以解决:

    def dig(collection, keys)
        if keys.length == 0 || collection == nil
            collection
        else
            dig(collection[keys[0]], keys.drop(1))
        end
    end
    

    另外值得注意的是dig 也存在于数组中,您可以在嵌套结构中混合使用数组和哈希映射,并使用dig 无缝遍历它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-26
      • 2012-11-25
      • 2013-11-25
      • 1970-01-01
      • 2013-12-18
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多