微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > Hashes of Hashes Idiom in Ruby?                                    3个
我习惯于在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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐