Is it good practice to initialize an accumulator like this?
100.times do
@accumulator = (@accumulator || 0) + 1
end
Or should I just initialize it outside the loop and do:
@accumulator = 0
100.times do
@accumulator += 1
end
Is it good practice to initialize an accumulator like this?
100.times do
@accumulator = (@accumulator || 0) + 1
end
Or should I just initialize it outside the loop and do:
@accumulator = 0
100.times do
@accumulator += 1
end
To directly answer your question, I'd normally initialize outside the loop.
However, I would say best practice is to use higher order functions in block form that negates the need for an explicit loop.
@accumulator = 100.times.reduce do |memo, element|
memo + element
end
Or, in this case you could even use a symbol to specify the method as so:
@accumulator = 100.times.reduce(:+)
This applies the "+" method to each pair in turn.
http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-reduce
I like the second one. but if you are looking for a acumulator for .times method you could use
100.times do |accumulator|
p accumulator
end
the only difference with yours examples is that you have an object attribute as accumulattor, so if you need that attibute for latter usage, you could do something like this
100.times do |c|
@accumulator = c
end