开发者

How do I iterate through an array of ranges in Ruby?

开发者 https://www.devze.com 2023-02-09 10:14 出处:网络
If you have an array of ranges, such as [1..4, 7..11, 14..18, 21..25, 28..28], what options do I have for iterating through the elements?

If you have an array of ranges, such as [1..4, 7..11, 14..18, 21..25, 28..28], what options 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开发者_运维技巧 bit verbose, or I could do

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

which could use a lot of memory if the ranges are large.

Are there any alternatives?


Well, I don't think your first answer is too verbose, but if that pattern is getting used often enough, it might make the case for 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
0

精彩评论

暂无评论...
验证码 换一张
取 消