Ruby undefined method `+' for nil:NilClass (NoMethodError)

北城余情 提交于 2019-12-10 09:42:56

问题


New to Ruby. Receiving error: undefined method `+' for nil:NilClass (NoMethodError)

I do not understand why I am receiving an error for such a simple task of incrementing a value. However, perhaps the error is caused by something else.

What is the cause?

class LinkedList
  class Node
    attr_accessor :data, :nextNode

    def initialize(data = nil, nextNode = nil)
      @data = data
      @nextNode = nextNode
    end
  end

#member variables
  @head = nil
  @size = 0

  def initialize
    @head = Node.new()
  end

  def add(val)
    curr = @head
    while curr.nextNode != nil
      curr = curr.nextNode
    end
    curr.nextNode = Node.new(val)
    @size += 1  #<<<-------------------------------------ERROR LINE----------
  end
end

list = LinkedList.new()
list.add(0)

回答1:


Move the declaration for @size into the initialize method:

def initialize(data = nil, nextNode = nil)
  @data = data
  @nextNode = nextNode
  @size = 0
end


来源:https://stackoverflow.com/questions/15182935/ruby-undefined-method-for-nilnilclass-nomethoderror

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!