如何在 Ruby 中迭代范围数组?

发布于 2024-10-17 06:29:11 字数 410 浏览 2 评论 0原文

如果您有一系列范围,例如 [1..4, 7..11, 14..18, 21..25, 28..28],我有哪些选项迭代元素?

我可以

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

这样做有点冗长,或者

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

如果范围很大,我可以这样做可能会使用大量内存。

还有其他选择吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

君勿笑 2024-10-24 06:29:11

好吧,我不认为你的第一个答案太冗长,但如果这种模式使用得足够频繁,它可能会证明这样的情况 -

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文