2016-10-18 4 views
2

私の目標は、候補者の投票を集計する投票機を作ることです。結局私は、書き込みにする候補のオプションを追加したいが、私はこのエラーでこだわっている:投票数を数える方法と、未定義のメソッド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 
+1

注:Rubyは、一般的にcast_vote' 'などのメソッド名を書くために人々を奨励しますそれはすべて小文字です。 – tadman

+0

"[ask]"と "[mcve]"をお読みください。私は "[スマートウェイの質問方法](http://catb.org/esr/faqs/smart-questions.html)"を読んで、今後の質問にお役立てください。 –

答えて

1

あなたはそれがそのクラスにどこでもnilをですので、あなたのinitialize方法で@countインスタンス変数を除外して初期化されることは決してありません:

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 
+1

理由は私は解決策に同意しません。 '@ count'は配列でなければならず、' totalVotes'メソッドは '@ count'の代わりに' @ count.length'をテストする必要があります。 – SparK

+0

残念ながら、 、それを指摘してくれてありがとう –

関連する問題