ruby adding range elements in each block

advertisements

How can I add range elements in each block together. E.g.:

a = [[1..10, 13..20, 21..24], [34..39, 42..45], [50..55]]

outcome:

a = [[9+7+3],[5+3],[5]]
a = [20, 8, 5]


You can access the first and last elements of a range by the corresponding first and last methods. inject(:+) sums up the partial distances of all the ranges belonging to the same group.

a.map { |ran­ges| range­s.map { |rang­e| range­.last - range­.first }.inj­ect(:+) }
=> [19, 8, 5]

Or, even shorter, as suggested by tokland using Ruby 2.0:

a.map { |ran­ges| range­s.map(&:size).reduce(0, :+) }