rubyinjectparallel-assignment

Ruby equilibrium index - odd usage of inject


I spent a bit of time today tackling the equilibrium index problem (described here)

After writing my own solution (which performed badly with large numbers), I decided to find one that would be a perfect score. I found this (which Codility scores as 100/100):

  def equi(a)
    left, right = 0, a.inject(0, &:+)
    indices = []
    a.each_with_index do |val, i|
      right -= val

      indices << i if right == left

      left += val
    end
    indices
  end

What I don't understand is the piece of parallel assignment and use of inject at the top of the method. Is anyone able to describe what this is doing?

Many thanks! Stu


Solution

  • It assigns 0 to left and the sum of a's elements to right. The 0 argument is there because otherwise an empty array would return nil. The shorthand used for summing is Symbol#to_proc and is unnecessary because inject directly takes a symbol as its argument - inject(0, :+).