如何从嵌套哈希中获取密钥或密钥的存在价值?

Ank*_*ria 1 ruby hash ruby-on-rails

如何从嵌套哈希中获取密钥的值或密钥的存在?

例如:

a = { "a"=> { "b" => 1, "c" => { "d" => 2, "e" => { "f" => 3 } }}, "g" => 4}
Run Code Online (Sandbox Code Playgroud)

有没有直接的方法来获得"f"的值?或者是否有一种方法可以知道嵌套哈希中是否存在密钥?

saw*_*awa 5

%w[a c e f].inject(a, &:fetch) # => 3
%w[a c e x].inject(a, &:fetch) # > Error key not found: "x"
%w[x].inject(a, &:fetch) # => Error key not found: "x"
Run Code Online (Sandbox Code Playgroud)

或者,为了避免错误:

%w[a c e f].inject(a, &:fetch) rescue "Key not found" # => 3
%w[a c e x].inject(a, &:fetch) rescue "Key not found"  # => Key not found
%w[x].inject(a, &:fetch) rescue "Key not found"  # => Key not found
Run Code Online (Sandbox Code Playgroud)