2010-02-02 52 views
1

有Array類我如何訪問數組的屬性在Ruby中

>> answers_to_problem 
=> [#<Answer id: 807, problem_id: 1, player_id: 53, code: "function y = times2(x 
)\r\n y = 2*x;\r\nend", message: nil, score: 12, output: nil, hide: nil, create 
d_at: "2010-02-02 11:06:49", updated_at: "2010-02-02 11:06:49", correct_answer: 
nil, leader: nil, success: true, cloned_from: nil>] 

的這個對象做一個二進制的檢查,我需要訪問成功場。我不知道我甚至在這裏使用正確的術語,所以我不能搜索如何訪問它。

answer_to_problems發現這樣:

answers_to_problem = Answer.find_all_by_problem_id_and_player_id(current_problem,player_id) 

最後,我想這樣做的檢查:

is_correct = (answers_to_problem.success == true) 

回答

3

這不是數組的屬性 - 它的對象的屬性在陣列中。所以你會這樣answers_to_problem[0].success訪問數組的第一個對象的success屬性。

+0

它是對象的數組,即使它是一個「標」。所以,這就是小規模啓蒙的感覺! – MatlabDoug 2010-02-02 18:33:27

2

您確定要使用find_all嗎?如果你知道你只會得到一個答案,你應該使用find而不是all。這樣你得到一個單一的Answer對象而不是一個數組。

如果你可以找回多個答案,你想檢查所有的答案是成功的還是隻是其中之一?

你可以做前者:answers.all?(&:success)和後者answers.any?(&:success)

+0

對於這種情況,可能會有多個結果。上面的檢查還有更多,首先檢查長度是否爲1.如果是,則檢查是否成功。我需要兩個實際。 您的解決方案適用於我遇到的許多相關問題! – MatlabDoug 2010-02-02 18:45:40

2

這裏的問題外一點,但:

is_correct = (answer_to_problem.success == true) 

在這裏,你正在做的任務和真相支票是不是真的需要。 is_correct在這裏只是反映任何answer_to_problem.success會。縮短:

answer_to_problem.success == true 

現在您仍在執行比較以獲取您已擁有的布爾值。縮短:

answer_to_problem.success 

有,你可以在你使用is_correct相同的方式使用的聲明。爲了使其更好看,你可以這樣做:

class Answer 
    def correct? 
    success 
    end 
end 

,只是使用answer_to_problem.correct?