Search code examples
rubycode-injectionenumerable

Conditional summarizing via inject


How to get the index of item in:

my_array.inject {|rs,item| rs += item}

I need to summarize all except the i-th element.


Solution

  • Just summarize over the indices.

    (0...a.size).inject(0) { |sum, index| if index != (i - 1) then sum + my_array[i] else sum }