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

我习惯于在 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';

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

更新

除了Douglas提出的解决方案(见下文)之外,我还找到了一个thread on the subject,其中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

它允许在仅在请求项目值时不期望地创建丢失的散列项目时解决问题,例如,关键’].

一些额外的参考

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

解决方法

试试这个:

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

a = hash_with_default_hash

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...