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.
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.
use index method of array:
>> arr = ['a','b', 'c','a']
=> ["a", "b", "c", "a"]
>> arr.index('a')
=> 0
>> arr.index('b')
=> 1
Just summarize over the indices.
(0...a.size).inject(0) { |sum, index| if index != (i - 1) then sum + my_array[i] else sum }
You would have to write your own (even in Ruby 1.9, since inject does not return an iterator).
module Enumerable
  def inject_with_index(injected)
    each_with_index {|value, index| injected = yield(injected, value, index)}
    injected
  end
end
Edit: If you switch inject and each_with_index around (thanks to the commenter!) you can do it without a new method:
["a", "b", "c"].each_with_index.inject("") do |result, (value, index)|
  index != 1 ? result + value : result
end
Make sure to return just result if you want to exclude the value. This also applies to the first method.
You could take out the item you don't want first:
my_array.values_at(0...i,(i+1)..-1).inject {|rs,item| rs += item}