开发者

How to access a property of an array in Ruby

开发者 https://www.devze.com 2022-12-19 12:05 出处:网络
I have this object of class Array >> answers_to_problem => [#<Answer id: 807, problem_id: 1, player_id: 53, code: \"function y = times2(x

I have this object of class 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"开发者_StackOverflow, updated_at: "2010-02-02 11:06:49", correct_answer:
nil, leader: nil, success: true, cloned_from: nil>]

For doing a binary check, I need access to the success field. I am not sure I am even using the right terminology here so I can not search how to access it.

answer_to_problems was found this way:

answers_to_problem = Answer.find_all_by_problem_id_and_player_id(current_problem,player_id)

Ultimately, I want to do this check:

is_correct = (answers_to_problem.success == true) 


That isn't a property of the array — it's a property of the object in the array. So you'd so answers_to_problem[0].success to access the success attribute of the first object of the array.


Are you sure, you want to use find_all? If you know you'll only get one Answer back, you should use find without the all. That way you get a single Answer object instead of an array.

If you can get back more than one answer, do you want to check that all the answers are successful or just that one of them is?

You can do the former with: answers.all?(&:success) and the latter with answers.any?(&:success).


A bit outside the question here, but:

is_correct = (answer_to_problem.success == true)

Here you are doing an assignment and a truth check which are not really needed. is_correct is here just reflecting whatever answer_to_problem.success would be. Shorten:

answer_to_problem.success == true

Now you're still performing a comparison to get a boolean value which you already have. Shorten:

answer_to_problem.success

There is a statement which you can use in the same manner you'd use is_correct. To make it read even better you could do:

class Answer
  def correct?
    success
  end
end

And just use answer_to_problem.correct?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号