Ruby:获取哈希中的所有键(包括子键) [英] Ruby: Get all keys in a hash (including sub keys)

查看:115
本文介绍了Ruby:获取哈希中的所有键(包括子键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们有这个哈希值:

hash = {"a" => 1, "b" => {"c" => 3}}
hash.get_all_keys 
=> ["a", "b", "c"]

由于hash.keys仅返回["a", "b"]

推荐答案

这将为您提供所有嵌套级别的所有键的数组.

This will give you an array of all the keys for any level of nesting.

def get_em(h)
  h.each_with_object([]) do |(k,v),keys|      
    keys << k
    keys.concat(get_em(v)) if v.is_a? Hash
  end
end

hash = {"a" => 1, "b" => {"c" => {"d" => 3}}}
get_em(hash) #  => ["a", "b", "c", "d"]

这篇关于Ruby:获取哈希中的所有键(包括子键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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