tags:

views:

96

answers:

4
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)

A: 

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
rogerdpack
A: 

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
bta
Yeah that is one way. I wonder if there is a more well, i don't know... poetic way to write it
Zombies
I suppose there's always `file = IO.readlines("filename")[3..-1]` (if all you want to do is ignore the first three lines and read in the rest)
bta
+4  A: 

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
Mladen Jablanović
Yes, this works in 1.8.7. Nicer than my answer: It says what it means.
Wayne Conrad
For MRI < 1.8.7, just require 'backports'.
Marc-André Lafortune
A: 

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
Andrew Grimm