是否定义了嵌套哈希?()

Bri*_*dan 3 ruby hash defined hash-of-hashes

什么是最简洁的方法来确定是否@hash[:key1][:key2]已定义,如果@hash@hash[:key1]为零,则不会抛出错误?

defined?(@hash[:key1][:key2])如果@hash[:key1]存在则返回True (它不确定是否:key2已定义)

Kon*_*ase 5

使用ActiveSupport(Rails)或Backports时,您可以使用try:

@hash[:key1].try(:fetch, :key2)
Run Code Online (Sandbox Code Playgroud)

你甚至可以处理@hash之中nil:

@hash.try(:fetch, :key1).try(:fetch, :key2)
Run Code Online (Sandbox Code Playgroud)

如果要@hash始终为缺少的键返回哈希值:

@hash = Hash.new { |h,k| h[k] = {} }
@hash[:foo] # => {}
Run Code Online (Sandbox Code Playgroud)

您还可以定义此递归:

def recursive_hash
  Hash.new { |h,k| h[k] = recursive_hash }
end

@hash = recursive_hash
@hash[:foo][:bar][:blah] = 10
@hash # => {:foo => {:bar => {:blah => 10}}}
Run Code Online (Sandbox Code Playgroud)

但要回答你的问题:

module HasNestedKey
  Hash.send(:include, self)
  def has_nested_key?(*args)
    return false unless sub = self[args.shift]
    return true if args.empty?
    sub.respond_to?(:has_nested_key?) and sub.has_nested_key?(*args)
  end
end

@hash.has_nested_key? :key1, :key2
Run Code Online (Sandbox Code Playgroud)