Search code examples
rubyloopsdry

How could I DRY this while loop?


I need to DRY this code but I don't know how.

I tried to dry the if condition but I don't know how to put the while in this.

def sum_with_while(min, max)
  # CONSTRAINT: you should use a while..end structure
  array = (min..max).to_a
  sum = 0
  count = 0
  if min > max
    return -1
  else
    while count < array.length
      sum += array[count]
      count += 1
    end
  end

  return sum
end

Solution

  • This is one option, cleaning up your code, see comments:

    def sum_with_while(range) # pass a range
      array = range.to_a
      sum, count = 0, 0 # parallel assignment
      while count < array.length
        sum += array[count]
        count += 1
      end
      sum # no need to return
    end
    
    
    sum_with_while(10..20)
    #=> 165
    


    More Rubyish:

    (min..max).sum