views:

100

answers:

4

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.

+2  A: 

use index method of array:

>> arr = ['a','b', 'c','a']
=> ["a", "b", "c", "a"]
>> arr.index('a')
=> 0
>> arr.index('b')
=> 1
Eimantas
+3  A: 

Just summarize over the indices.

(0...a.size).inject(0) { |sum, index| if index != (i - 1) then sum + my_array[i] else sum }
Dario
Thanks, but it looks like there's simpler way:my_arr.inject {|rs,item| rs += item if my_arr.index(item)!= 0}
gmile
But the simpler way you suggested is dangerous with duplicate items and much less performant - Element lookup requires O(n).
Dario
+1  A: 

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.

gix
`each_with_index.inject` works fine in 1.8.7+
sepp2k
You're right, I didn't think of switching both. But you have to put the arguments in parentheses.
gix
+2  A: 

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}
glenn mcdonald
Best solution, I think
Dario