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

时间:2010-02-02 18:26:34

标签: ruby arrays

我有类Array

的这个对象
    >> 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 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

如果您可以找回多个答案,是否要检查所有答案是否成功,还是只检查其中一个答案?

您可以使用answers.all?(&:success)执行前者,使用answers.any?(&:success)执行后者。

答案 2 :(得分: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?

即可