在.each循环中处理1000行,如何每100个项输出一次put消息?

Bla*_*man 0 ruby

我正在.each循环中处理1000个用户对象.

我想输出一条put消息以反馈给控制台.

我怎么能这样做,什么是Ruby模数运算符?

我试过了:

if u.id % 100
   puts u.id.to_s
end
Run Code Online (Sandbox Code Playgroud)

Phi*_*lip 7

试试看::-)

if u.id % 100 == 0
   puts u.id.to_s
end
Run Code Online (Sandbox Code Playgroud)


the*_*Man 5

这将循环2000次,每100个循环输出一个标准消息:

1.upto(2000).with_index do |j,i|
  print "line #{i}\r" if (i % 100 == 0)
end
print "\ndone\n"
Run Code Online (Sandbox Code Playgroud)

这种进度指标的替代方案是:

print '.' if (i % 100 == 0)
Run Code Online (Sandbox Code Playgroud)

或简单的微调器:

spinner = %w[ | / - \\ ]
1.upto(n).with_index do |j,i|
  print spinner.rotate![0], "\r" if (i % 100 == 0)
  # some long running task
end
print "\ndone\n"
Run Code Online (Sandbox Code Playgroud)

注意 - 如果您.id来自通过读取数据库中的行而创建的ActiveRecord对象,那么如果您的排序不是基于id列,则循环时可能会出现大幅变化的输出.此外,如果您的数据库已存在一段时间并且您一直在删除行,则可能存在id数字空白.最终结果是你的"每100个"可能非常不准确.

我建议不要比较id,而是使用一个单独的变量,在循环时递增,或使用each_with_index或Enumerable's with_index为您提供可用于% 100 == 0测试的一致递增的数字.