【发布时间】: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'].
一些额外的参考资料
【问题讨论】:
-
我是一名 PHP 人,对 Ruby 知之甚少,但在我看来,这是 PHP 的可怕特性之一,不应该被导出到其他语言中。 :) (虽然我明白为什么在这种情况下会想要它。)
标签: php ruby hash initialization multidimensional-array