【问题标题】:Is auto-initialization of multi-dimensional hash array possible in Ruby, as it is in PHP? [duplicate]在 Ruby 中是否可以像在 PHP 中那样自动初始化多维哈希数组? [复制]
【发布时间】:2011-03-10 02:10:18
【问题描述】:

我习惯于在 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 中做类似的事情?或者我需要先初始化所有维度,然后再赋值。是否可以定义一个允许做我需要的高级哈希?你会怎么做?


更新

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

当仅请求项值时不希望创建缺少的哈希项时,它允许解决问题,例如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

【问题讨论】:

  • 我是一名 PHP 人,对 Ruby 知之甚少,但在我看来,这是 PHP 的可怕特性之一,不应该被导出到其他语言中。 :) (虽然我明白为什么在这种情况下会想要它。)

标签: php ruby hash initialization multidimensional-array


【解决方案1】:

试试这个:

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

a = hash_with_default_hash

如果键不存在,那么块的结果将被用作默认值。在这种情况下,默认值也是一个使用哈希作为默认值的哈希。

【讨论】:

  • 它就像一个魅力!谢谢你,道格拉斯
  • 还有一件事希望 - 如果我只检查项目值 a['key'],那么将创建一个带有键 key 的新项目以防它不存在。如何避免这种行为?
  • 你在 Hash#has_key 之后? ruby-doc.org/core/classes/Hash.html#M002883
  • 你说得对,我需要它主要用于if 句子,而应该使用Hash#has_key? 代替。试图改变我的 PHP 实践...
猜你喜欢
  • 1970-01-01
  • 2012-03-20
  • 2010-10-19
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多