当条件满足时,打破Ruby Find.find循环

时间:2022-12-03 10:23:48

I'm iterating through a large directory of files with:

我正在迭代一个大的文件目录:

Find.find('/some/path/to/directory/root') do |path|
  # ...do stuff with files…
end

What's a good way to limit the size of this enumerable group to 500 (or break out in some other way) if, say, Rails.env.development??

如果Rails.env.development ??将这个可枚举组的大小限制为500(或以其他方式突破)有什么好方法?

I could use a counter but what's "the Ruby way"?

我可以使用一个计数器但是什么是“Ruby方式”?

2 个解决方案

#1


2  

This is one way:

这是一种方式:

Find.find('/some/path/to/directory/root').first(500).each do |path|
  # do something
end

#2


1  

Find.find enumerates the files; In other words it wants to loop over all of them. You can tack on an index value using:

Find.find枚举文件;换句话说,它想要遍历所有这些。您可以使用以下方法来处理索引值:

Find.find(ENV['HOME']).with_index(1) do |path, i|
  puts path
  break if i > 10
end

puts 'done'

and use that to keep track of how many you've processed.

并用它来跟踪你处理的数量。

If you want to "do 'em all":

如果你想“全部做”:

limit = <some number>

do_em_all = (limit == 0)
Find.find(ENV['HOME']).with_index(1) do |path, i|
  puts path
  break unless (do_em_all || i <= limit)
end

puts 'done'

If limit is 0 you'll process everything. If it's > 0 you'll loop limit times.

如果limit为0,您将处理所有内容。如果它> 0,你将循环限制时间。

You can also use Dir.entries or Dir.glob which will return an array of entries that you can slice apart as you want.

您还可以使用Dir.entries或Dir.glob,它将返回您可以根据需要切片的条目数组。

Enumerable's each_slice could be useful at that point.

在这一点上,Enumerable的each_slice可能很有用。

#1


2  

This is one way:

这是一种方式:

Find.find('/some/path/to/directory/root').first(500).each do |path|
  # do something
end

#2


1  

Find.find enumerates the files; In other words it wants to loop over all of them. You can tack on an index value using:

Find.find枚举文件;换句话说,它想要遍历所有这些。您可以使用以下方法来处理索引值:

Find.find(ENV['HOME']).with_index(1) do |path, i|
  puts path
  break if i > 10
end

puts 'done'

and use that to keep track of how many you've processed.

并用它来跟踪你处理的数量。

If you want to "do 'em all":

如果你想“全部做”:

limit = <some number>

do_em_all = (limit == 0)
Find.find(ENV['HOME']).with_index(1) do |path, i|
  puts path
  break unless (do_em_all || i <= limit)
end

puts 'done'

If limit is 0 you'll process everything. If it's > 0 you'll loop limit times.

如果limit为0,您将处理所有内容。如果它> 0,你将循环限制时间。

You can also use Dir.entries or Dir.glob which will return an array of entries that you can slice apart as you want.

您还可以使用Dir.entries或Dir.glob,它将返回您可以根据需要切片的条目数组。

Enumerable's each_slice could be useful at that point.

在这一点上,Enumerable的each_slice可能很有用。