Skip to content

Instantly share code, notes, and snippets.

Created October 29, 2016 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1ac8faf81bbd6f9fac2cd3539270b701 to your computer and use it in GitHub Desktop.
Save anonymous/1ac8faf81bbd6f9fac2cd3539270b701 to your computer and use it in GitHub Desktop.
def total_weight(quiz)
weight = 0
quiz.questions.each do |question|
weight += question.weight if question.present?
end
weight
end
@patricknpinto
Copy link

If you are working with ActiveRecord you can do quiz.questions.sum(:weight)
If not you can use the reduce method (https://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-reduce):

def total_weight(quiz)
  questions = quiz.questions.compact # remove nil questions
  questions.reduce(0) { |sum, question| sum + question.weight }
end

@jlm
Copy link

jlm commented Oct 31, 2016

Thanks for this interesting answer!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment