gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:45 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com