简体   繁体   English

从 class 外部访问实例变量

[英]Accessing instance variables from outside the class

I'm having issues understanding this encapsulation.我在理解这种封装时遇到问题。 I have instance variables defined with attr_accessor.我有用 attr_accessor 定义的实例变量。 I'm trying to access them outside class.我正在尝试在 class 之外访问它们。 But they are always nil and returns undefined method.但它们总是 nil 并返回未定义的方法。

NoMethodError: undefined method `has_key?' NoMethodError:未定义的方法“has_key?” for nil:NilClass对于零:NilClass

Please help me understand.请帮我理解。

class TrieNode
    attr_reader :value, :next, :children
    
    def initalize
        @value = nil
        @children = Hash.new
        @next = nil
    end
end

class Trie
    attr_accessor :root
    
    def initialize
        @root = TrieNode.new
    end
    
    def build_trie(strs)
        cur = @root
        
        strs.each do |str|
            str.chars.each do |char|
                if cur.children.has_key? char
                    cur = cur.children[char]
                    next
                else
                    new_node = TrieNode.new
                    cur.children[char] = new_node
                    cur = new_node
                end
            end
          cur = @root
        end
    end
end

Yes, it is not encapsulation, it is because your object is not instantiated properly, which is caused by a typo是的,不是封装,是因为你的object没有正确实例化,是错字造成的

  def initalize
        @value = nil
        @children = Hash.new
        @next = nil
  end

should be initialize not initalize应该initialize而不是initalize

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM