tags:

views:

118

answers:

3

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", 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) 
+3  A: 

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.

Chuck
It is an array of objects, even though it is a 'scalar'. So, this is what enlightenment feels like on a very small scale!
MatlabDoug
+2  A: 

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

sepp2k
For this case, there could be multiples results. There is more to the check above, first I check to see if the length is == 1. If it is, then I check for success. I need both actually.Your solution is good for many related problems I am running into!
MatlabDoug
+1  A: 

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?

runeb