我如何访问数组的属性在Ruby中

问题描述:

有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) 

这不是数组的属性 - 它的对象的属性在阵列中。所以你会这样answers_to_problem[0].success访问数组的第一个对象的success属性。

+0

它是对象的数组,即使它是一个“标”。所以,这就是小规模启蒙的感觉! – MatlabDoug 2010-02-02 18:33:27

您确定要使用find_all吗?如果你知道你只会得到一个答案,你应该使用find而不是all。这样你得到一个单一的Answer对象而不是一个数组。

如果你可以找回多个答案,你想检查所有的答案是成功的还是只是其中之一?

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

+0

对于这种情况,可能会有多个结果。上面的检查还有更多,首先检查长度是否为1.如果是,则检查是否成功。我需要两个实际。 您的解决方案适用于我遇到的许多相关问题! – MatlabDoug 2010-02-02 18:45:40

这里的问题外一点,但:

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?