Ruby:如何“下一步”外部循环?

发布于 2024-08-25 02:08:08 字数 220 浏览 5 评论 0原文

file.each_line do |line|
  #skip the first one/not a user
  3.times { next } if first == 1
  first = 2
end

如何获得“下一个”,“下一个”each_line 的迭代,而不是 3.times 迭代?另外,我怎样才能写这个看起来更好(即:first == 1看起来很糟糕)

file.each_line do |line|
  #skip the first one/not a user
  3.times { next } if first == 1
  first = 2
end

How can I get the 'next' to well, "next" the iteration of the each_line, instead of the 3.times iteration? Also, how can I write this to look better (ie: first == 1 looks bad)

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

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

发布评论

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

评论(4

永言不败 2024-09-01 02:08:08

您可以使用 drop 方法来删​​除前几个元素:

File.open('bar').each_line.drop(3).each do |line|
  puts line
end

You can use drop method to, er, drop first couple of elements:

File.open('bar').each_line.drop(3).each do |line|
  puts line
end
一指流沙 2024-09-01 02:08:08

您的内部循环可以在 break 之前设置一个标志变量(例如 break_out = true),并且您可以在退出内部循环后立即检查该变量。如果检测到该标志已设置,则跳出外循环。

更有可能的是,有一种更好的方法来构建您的代码来完成您想要的事情。您只是想跳过前三行吗?如果是这样,请尝试以下操作:

line_count = 0
file.each_line do |line|
  #skip the first one/not a user
  line_count += 1
  next if (line_count <= 3 && first == 1)
  first = 2
end

Your inner loop can set a flag variable (say, break_out = true) before it breaks and you can check that variable as soon as you come out of the inner loop. If you detect the flag is set, break out of the outer loop.

More likely, there is a better way of structuring your code to do what you want. Are you simply wanting to skip the first three lines? If so, try something like:

line_count = 0
file.each_line do |line|
  #skip the first one/not a user
  line_count += 1
  next if (line_count <= 3 && first == 1)
  first = 2
end
黑凤梨 2024-09-01 02:08:08

我认为你需要在其中添加另一个 if 语句

file.each_line do |line|
  #skip the first one/not a user
  3.times { next } if first == 1
  break if something
  first = 2
end

I think you'll need to add another if statement in there

file.each_line do |line|
  #skip the first one/not a user
  3.times { next } if first == 1
  break if something
  first = 2
end
浴红衣 2024-09-01 02:08:08

如果文件不是太大,你可以这样做

file.read.split("\n")[3..-1].each do |line_you_want|
  puts line_you_want
end

If the file isn't too large, you can do

file.read.split("\n")[3..-1].each do |line_you_want|
  puts line_you_want
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文