简体   繁体   中英

Accessing instance variables from outside the class

I'm having issues understanding this encapsulation. I have instance variables defined with attr_accessor. I'm trying to access them outside class. But they are always nil and returns undefined method.

NoMethodError: undefined method `has_key?' for nil: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

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

should be initialize not initalize

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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