如何访问和比较两个数组

时间:2015-09-15 09:07:15

标签: ruby-on-rails arrays ruby

通过这些方法,我得到了两个数组:

@correct_answer = Question.pluck(:correct_answer)
# => [1, 1, 2, 2, 1, 1, 3, 1, 3]
@selected_answer = Question.pluck(:selected_answer)
# => [1, 4, 3, 1, 1, 3, 4, 1, 1]

如何逐个比较这两个数组中的值?我使用这段代码:

if @correct_answer[0] == @selected_answer[0]
  @result += 1
else
  @result -= 1
end   

但那不起作用。

4 个答案:

答案 0 :(得分:2)

编辑:您可以通过这种方式计算正确答案:

correct_score = correct_answer.zip(selected_answer).count { |correct, wrong| correct == wrong }
# => 3
wrong_score = selected_answer.size - correct_score
# => 6
total_score = correct_score - wrong_score
# => -3

您还可以通过此代码找出匹配的值:

correct_answer = [1, 1, 2, 2, 1, 1, 3, 1, 3]
# => [1, 1, 2, 2, 1, 1, 3, 1, 3]
selected_answer = [1, 4, 3, 1, 1, 3, 4, 1, 1]
# => [1, 4, 3, 1, 1, 3, 4, 1, 1]
correct_answer.zip(selected_answer).map do |correct, selected| 
  correct == selected ? 'Correct!' : "Wrong! Correct answer is: #{correct}" 
end
# => ["Correct!", "Wrong! Correct answer is: 1", "Wrong! Correct answer is: 2", "Wrong! Correct answer is: 2", "Correct!", "Wrong! Correct answer is: 1", "Wrong! Correct answer is: 3", "Correct!", "Wrong! Correct answer is: 3"]

答案 1 :(得分:1)

这是一个可能的解决方案

a1 = [1, 1, 2, 2, 1, 1, 3, 1, 3]
a2 = [1, 4, 3, 1, 1, 3, 4, 1, 1]

a1.zip(a2).inject(0) do |result, (correct, selected)|
  result += (correct == selected ? 1 : -1)
end
# => -3 

解释:

  • zip您将a1a1合并到一个数组中。
  • 您使用inject从基值0
  • 开始映射和缩小数组
  • 如果值匹配,则添加+1,否则为-1

答案 2 :(得分:0)

你可以试试这个。

@selected_answers = [1, 4, 3, 1, 1, 3, 4, 1, 1]
@correct_answers = [1, 1, 2, 2, 1, 1, 3, 1, 3]

## This will return count of all matched and unmatched values.
@selected_answers.each_with_index do |selected_answer, index|
  if selected_answer == @correct_answers[index]
    @result += 1
  else
    @result -= 1
  end
end

## This will return count of only matched values.
@selected_answers.each_with_index do |selected_answer, index|
  @result += 1 if selected_answer == @correct_answers[index]
end

答案 3 :(得分:0)

@result = 0
@correct_answer = Question.pluck(:correct_answer)
@selected_answer = Question.pluck(:selected_answer)
@selected_answer.each_with_index do |selected_answer, index|
  @result += 1 if selected_answer == @correct_answer[index]
end  

感谢Amit sharma,这段代码对我有用。