0

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
Dorsal6
  • 13
  • 2

2 Answers2

2

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

adzdavies
  • 1,545
  • 1
  • 13
  • 13
0

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
Horacio
  • 2,865
  • 1
  • 14
  • 24