Question

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]
Was it helpful?

Solution

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, :+) }

OTHER TIPS

Ruby 2.0:

a.map { |ranges| ranges.map { |r| r.size - 1 } .reduce(0, :+) }

Range class has a method called #size. Thus we can do as :

a.map { |ranges| ranges.inject(0) { |sum,rng| sum + rng.size - 1 } }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top