In Ruby, should I use control flow to initialize an accumulator inside a loop?

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

Answers


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

Need Your Help

Use Ajax or jQuery to Make Table Element in Rails App Load Separate From Page

javascript jquery ruby-on-rails ajax coffeescript

I have a page with a list of user sites and on it I am making an API call to check the status of something for each site. The problem is that it makes the page take forever to load, so I would like...

How to manage Activity stacks?

android android-activity back-stack

I have a basic questions and looking for the "best practice" on how to handle that.