From: Daniel Berger Date: 2005-07-15T03:59:45+09:00 Subject: Re: Help: very simple script problem Tristan Knowles wrote: > Just another quick question regarding flow control. > > What variable can I refer to, and what method do I use > to create a while loop so that only x amount of lines > are shown at once from a file? > > This is how I have been approaching it, its obviously > not working, and I'm still not up to speed at working > out how to use methods based on the online reference > details only. > > ===== > if File.exists? Log_File > lines = File.open(Log_File).readlines > lines.each_with_index do |line, index| > index % 2 == 0 ? color = "#dddddd" : > color="#cccccc" > > while index <= 50 > > puts "\n > #{index}\n #{line}" > puts "" > > end > > end > ===== > > > Am I even approaching this the correct way? Or should > this be handled once step before with a grep > statement? Your code looks fine as is, although I wonder if 50 is a constant number you can rely on. But, here's some more info for you: If you only want 1 line per iteration, then your best bet is to use IO.foreach. If you only want to slurp X number of lines into a variable, then just keep in mind that IO.readlines returns an array. So, you can use a range as the index and do: # No need to use the File class, btw lines = IO.readlines(Log_File)[0..49] Just keep in mind that, even though you're only selecting 50 lines, the entire file has been slurped into memory. Regards, Dan