如何在 Ruby 中迭代范围数组?
如果您有一系列范围,例如 [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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我不认为你的第一个答案太冗长,但如果这种模式使用得足够频繁,它可能会证明这样的情况 -
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 -