Ruby Recursion Counter Without Global Variable

advertisements

I am trying to count the number of times the method recurses during the life of the program. The code below gets the desired result, but uses global variables. Is there a way around this or a better way?

$count = 0
def AdditivePersistence(num)
  return 0 if num.to_s.length == 1
  numarr = num.to_s.chars.map!(&:to_i)
  i = numarr.inject(&:+)
  $count+=1
    if i.to_s.length!=1
    AdditivePersistence(i)
    end
  $count
end


Since you want the total number of recursive calls during the lifetime of the program, a global variable in some form is the only way you can do it. You can either use an explicit global variable, as you have done, or a global variable in disguise, such as a singleton class, or a thread-local variable. I will not illustrate those here since they are inferior to plain global variables for this use case.