在Ruby中如何使用键路径(key path)遍历嵌套哈希映射(hash map)
Ruby 嵌套哈希任意层级取值解决方案
Ruby 2.3 及以上版本内置了Hash#dig原生方法,完全满足你的需求,直接传入任意长度的键序列即可访问对应嵌套层级的值,中途遇到不存在的键会直接返回nil,不会抛出异常:
# 调用示例 nested_hash.dig(:bar, :bar, :bar, :foo) # 返回最内层的foo对应值bar nested_hash.dig(:foo) # 返回第一层的foo对应值 nested_hash.dig(:bar, :invalid_key) # 键不存在时返回nil
如果你的键路径已经封装为数组,用展开运算符拆解后传入即可:
key_path = [:bar, :bar, :foo] nested_hash.dig(*key_path)
如果需要兼容 Ruby 2.3 以下的版本,也可以自己实现通用的嵌套取值方法:
def get_nested_value(hash, *key_path) # 无安全导航运算符的老Ruby版本可替换为:key_path.inject(hash) { |res, key| res ? res[key] : nil } key_path.inject(hash) { |res, key| res&.[](key) } end # 调用示例 get_nested_value(nested_hash, :bar, :foo) get_nested_value(nested_hash, *[:bar, :bar, :bar, :foo])
该实现支持任意长度的键路径,不需要提前固定层级,可扩展性强,同时支持传入任意哈希实例,刚好匹配你需要从多个不同数据结构拉取数据的需求。
内容的提问来源于stack exchange,提问作者Erik B
相关产品推荐
相关产品推荐

