How to iterate over an array of ranges in Ruby?

If you have an array of ranges, for example [1..4, 7..11, 14..18, 21..25, 28..28] , what parameters do I have for iterating through the elements?

I could do

 ranges.each do |range| range.each do |date| puts "Do work on February #{date}" end end 

which is a little detailed, or I could do

 dates = ranges.map(&:to_a).flatten dates.each do |date| puts "Do work on February #{date}" end 

which can use large memory if the ranges are large.

Are there any alternatives?

+4
source share
1 answer

Well, I don’t think your first answer is too verbose, but if this template gets used often enough, it can do it something like this:

 module Enumerable def each_node each do |x| (x.respond_to?(:each_node)) ? x.each_node{ |y| yield(y) } : yield(x) end end end [[[(1..5)], (1..2)],1].each_node { |x| print x } #=> 12345121 ranges = [1..4, 7..11, 14..18, 21..25, 28..28] ranges.each_node{ |date| puts "Do work on February #{date}" } #=>as expected 
+5
source

Source: https://habr.com/ru/post/1339135/


All Articles