Ruby inject until sum exceeds a set value and return the index where this occurs
With the following array and value: v = 50 a = [10, 20, 25, 10, 15] I want to iterate through the array adding up the values until the sum of these values exceeds the variable v. And then I want to be able to return the index in the array where that occurred. so... 10 + 20 + 25 = 55 (which is the first point which the sum is greater that 'v') so index = 2 Thanks for your help For the sum: a.inject do |sum,n| break sum if sum > v sum + n end For the index, idea is the same - you use the memo as an array and keep the sum in the first element: a.inject([0,-1]) do |memo,n| break [memo[0], memo[1]]