开发者

Ruby: How to 'next' an external loop?

开发者 https://www.devze.com 2022-12-22 19:16 出处:网络
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.tim
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)


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


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消