私の目標は、候補者の投票を集計する投票機を作ることです。結局私は、書き込みにする候補のオプションを追加したいが、私はこのエラーでこだわっている:投票数を数える方法と、未定義のメソッドpushを使って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
注:Rubyは、一般的にcast_vote' 'などのメソッド名を書くために人々を奨励しますそれはすべて小文字です。 – tadman
"[ask]"と "[mcve]"をお読みください。私は "[スマートウェイの質問方法](http://catb.org/esr/faqs/smart-questions.html)"を読んで、今後の質問にお役立てください。 –