Ruby undefined method `+' for nil:NilClass (No

2019-05-11 19:01发布

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)

标签: ruby numbers add
1条回答
贪生不怕死
2楼-- · 2019-05-11 19:43

Move the declaration for @size into the initialize method:

def initialize(data = nil, nextNode = nil)
  @data = data
  @nextNode = nextNode
  @size = 0
end
查看更多
登录 后发表回答