Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = (0..9).to_a

def split_and_sum array, *split_indexes
  # We always want to start with 0..(first split)
  ranges = [0..split_indexes.first]
  # Now run through the rest of the indexes until we reach
  # the end, at which point use the last index in the array
  split_indexes.each_with_index do |v, i|
    n = split_indexes[i+1] || array.length-1
    ranges << (v+1..n)
  end
  # For each range, sum that section of the array
  # and return the entire array
  ranges.map do |r|
    array[r].inject(&:+)
  end
end

split_and_sum(a, 4) # => [10, 35]
split_and_sum(a, 4, 6) # => [10, 11, 24]
split_and_sum(a, 4, 5) # => [10, 5, 30]