Lets say we have a loop in our controller, that's going through an array of numbers, checking whether they're even or odd:
[1,2,3,4,5].each do |number|
if number.odd?
@odd_count += 1
else
@even_count += 1
end
end
My question is if there's a way to do this array without previously setting the @odd_count and @even_count variables? If you execute the previous code block in a controller, you get
undefined method `+' for nil:NilClass
but I do not really want to do
@odd_count = 0
@even_count = 0
before the loop, because it's extra lines of code that don't look nice. For the sake of the question, let's say we have 10 different things we want to count, not 2.
Aucun commentaire:
Enregistrer un commentaire