是否可以在Ruby中自动初始化多维哈希数组,就像在PHP中一样?

And*_*rei 5 php ruby hash initialization multidimensional-array

我习惯于在PHP中使用多维数组,在那里我可以通过分配和初始化哈希

unset($a); // just to show that there is no variable $a
$a['settings']['system']['memory'] = '1 Gb';
$a['settings']['system']['disk space'] = '100 Gb';
Run Code Online (Sandbox Code Playgroud)

有没有办法在Ruby中做类似的事情?或者我需要先初始化所有维度,然后分配值.是否可以定义一个高级Hash,它可以满足我的需求?你会怎么做?


更新

除了道格拉斯提出的解决方案(见下文)之外,我还找到了一个主题,其中BrianSchröäer提出了该Hash课程的扩展:

class AutoHash < Hash
  def initialize(*args)
    super()
    @update, @update_index = args[0][:update], args[0][:update_key] unless args.empty?
  end

  def [](k)
    if self.has_key?k
      super(k)
    else
      AutoHash.new(:update => self, :update_key => k)
    end
  end

  def []=(k, v)
    @update[@update_index] = self if @update and @update_index
    super
  end
end
Run Code Online (Sandbox Code Playgroud)

当仅仅请求项目值时,例如,当不期望地创建丢失的散列项时,它允许解决该问题a['key'].


一些额外的参考

  1. ruby hash autovivification(facets)
  2. http://trevoke.net/blog/2009/11/06/auto-vivifying-hashes-in-ruby/
  3. http://www.eecs.harvard.edu/~cduan/technical/ruby/ycombinator.shtml

Dou*_*las 7

试试这个:

def hash_with_default_hash
    Hash.new { |hash, key| hash[key] = hash_with_default_hash }
end

a = hash_with_default_hash
Run Code Online (Sandbox Code Playgroud)

如果密钥不存在,则块的结果将用作默认值.在这种情况下,默认值也是使用散列作为其默认值的散列.