nil:NilClass 如何计票,如何处理未定义的方法 'push'

How to count votes, and deal with undefined method 'push' for nil:NilClass

我的目标是制作一个投票机,将候选人的选票计入总数。最后我想添加写入候选人的选项,但我遇到了这个错误:

undefined method 'push' for nil:NilClass) at line 30.

我定义了castVote,为什么没有被识别?

class Candidate
  attr_accessor :name
  attr_accessor :count, :total

  def initialize(cname)
    @name = cname
    @vote = Array.new
  end

  def totalVotes
    sum = 0
    if @count > 0
      @count.each { |c| sum += c }
      @total = sum
    else
      @total = 0
    end
  end


    def castVote(vote)
      if vote.is_a?(Integer) || vote.is_a?(Float)
      @count.push(vote)
      totalVotes
    end
  end

    #Candidate
    candidate1 = Candidate.new("Donald Duck")
    #Next line is where error occurs
    candidate1.castVote(1)
    candidate1.castVote(1)

    candidate2 = Candidate.new("Minnie Mouse")
    candidate2.castVote(1)

    candidate3 = Candidate.new("Goofy")

    finalResults = Array.new
    finalResults[0] = candidate1
    finalResults[1] = candidate2
    finalResults[2] = candidate3

    finalResults.each { |candidate| puts "Name: " + candidate.name + "Score " + candidate.totalVotes }
end

您在 initialize 方法中遗漏了 @count 实例变量,因此它在 class 中无处不在,并且永远不会被初始化:

class Candidate
  attr_accessor :name
  attr_accessor :count, :total

  def initialize(cname)
    @name = cname
    @vote = Array.new
    @count = []
  end

  def totalVotes
    sum = 0
    if @count.length > 0
      @count.each { |c| sum += c }
      @total = sum
    else
      @total = 0
    end
  end


    def castVote(vote)
      if vote.is_a?(Integer) || vote.is_a?(Float)
      @count.push(vote)
      totalVotes
    end
  end

    #Candidate
    candidate1 = Candidate.new("Donald Duck")
    #Next line is where error occurs
    candidate1.castVote(1)
    candidate1.castVote(1)

    candidate2 = Candidate.new("Minnie Mouse")
    candidate2.castVote(1)

    candidate3 = Candidate.new("Goofy")

    finalResults = Array.new
    finalResults[0] = candidate1
    finalResults[1] = candidate2
    finalResults[2] = candidate3

    finalResults.each { |candidate| puts "Name: " + candidate.name + "Score " + candidate.totalVotes }
end