Zombies
Zombies

Reputation: 25912

Ruby: How to 'next' an external loop?

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)

Upvotes: 2

Views: 1969

Answers (4)

Andrew Grimm
Andrew Grimm

Reputation: 81651

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

Upvotes: 0

Mladen Jablanović
Mladen Jablanović

Reputation: 44110

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

Upvotes: 6

bta
bta

Reputation: 45087

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

Upvotes: 1

rogerdpack
rogerdpack

Reputation: 66921

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

Upvotes: 0

Related Questions