Is auto-initialization of multi-dimensional hash array possible in Ruby, as it is in PHP?(在 Ruby 中是否可以像在 PHP 中那样自动初始化多维哈希数组?)
问题描述
我习惯于在 PHP 中使用多维数组,我可以在其中分配和初始化散列
I am so used to work in PHP with multi-dimensional arrays, where I can assign and initialize a hash by
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 中做类似的事情?或者我需要先初始化所有维度,然后再赋值.是否可以定义一个高级哈希来执行我需要的操作?你会怎么做?
Is there a way to do similar thing in Ruby? Or I need to initialize all dimensions first, and then to assign values. Is it possible to define an advanced Hash which will allow to do what I need? How would you do that?
更新
除了Douglas提出的解决方案(见下文),我还找到了一个该主题的线程,其中 Brian Schröäer 提出了 Hash
类的扩展:
In addition to the solution proposed by Douglas (see below), I have found a thread on the subject, in which Brian Schröäer has proposed an extension for the Hash
class:
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']
.
It allows to solve the problem when a missing hash item is undesirably created when the item value was only requested, e.g. a['key']
.
一些额外的参考资料
- ruby 哈希自动激活(方面)
- 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
如果键不存在,则块的结果将用作默认值.在这种情况下,默认值也是一个散列,它使用散列作为其默认值.
If the key doesn't exist, then the result of the block will be used as the default value. In this case, the default value is also a hash which uses hashes as its default values.
这篇关于在 Ruby 中是否可以像在 PHP 中那样自动初始化多维哈希数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Ruby 中是否可以像在 PHP 中那样自动初始化多维
基础教程推荐
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01