ruby - 如何统计选票,处理未定义方法 'push'为nil :NilClass

标签 ruby class push nomethoderror

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

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 实例变量,因此它在该类中的所有地方都是 nil 并且永远不会被初始化:

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

关于ruby - 如何统计选票,处理未定义方法 'push'为nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117727/

相关文章:

java - “Could not find or load main class”是什么意思?

c++ - 使用 istream 参数读取的 istream 函数

javascript - 将结果推送到数组

jquery - 随机延迟后添加类

android - Urban Airship - Push Sample => APID is everytime null

objective-c - 如何将标题设置为 leftBarButtonItem

ruby-on-rails - 在一行中删除多个 Rails session 变量

java - 搞乱 PATH 后找不到 Rake 命令 - 另外,rails 命令也不起作用

ruby 默认参数习语

ruby - Cucumber 2.0.0 与 RubyMine 6.x 和 TeamCity 格式化程序不兼容