加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:26:22 所属栏目:百科 来源:网络整理
导读:我习惯于在 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中做类似的
我习惯于在 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读