【问题标题】:Is there a way to initialize all child node of a hash?有没有办法初始化哈希的所有子节点?
【发布时间】:2015-12-12 12:01:30
【问题描述】:

必须一直初始化子元素只是多余的。我的意思是:

@parent = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }

如果我尝试创建另一个多维节点,我会尝试编码:

@parent[:child][some_field] = "Some example data..."

我总是收到这个错误:

undefined method `[]=' for nil:NilClass (NoMethodError)

你有什么办法解决这个问题吗?

【问题讨论】:

  • 这对我有用:parent = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }; parent[:child][:some_field] = 4。你能给我们更精确的步骤来重现问题吗?
  • 你有什么default_proc?
  • 你使用什么 Ruby 版本?
  • 哈希的构造函数是正确的,我怀疑像@parent[:child] = nil这样的东西发生在代码的某个地方
  • 我认为你是对的。配置是正确的,经过一番测试,我找到了罪魁祸首。事实证明,上面的 @parent 示例没有使用 Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) } 而不是来自 simple_xlsx_reader 的对象。我正在构建的应用程序是一个生成器,如果没有找到参数,将使用上面给定的示例。

标签: ruby hash


【解决方案1】:

我更需要嵌套哈希,为什么不定义自己的类?

class NestedHash < Hash  
  def initialize
    super { |h,k| h[k] = Hash.new(&h.default_proc) }
  end
end

h = NestedHash.new
h[:foo][:bar] = :baz
h[:foo][:bar] #=> :baz

【讨论】:

    【解决方案2】:

    有点类似于 spickermann 的回答,但有点不同。

    class MyHash < Hash
      def initialize
        self.default_proc = proc{|h, k| h[k] = MyHash.new}
      end
    end
    
    @parent = MyHash.new
    

    请注意,无需将参数/块传递给MyHash.new,因为设置不同的默认值会破坏使用MyHash 的目的,而Hash 会更适合这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 2021-06-09
      • 2012-11-14
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      相关资源
      最近更新 更多