From: Mark Sparshatt Date: 2004-07-24T20:22:06+09:00 Subject: Re: The number of lines of a file? polarpolar wrote: >Hi, Ruby Fans : > >I would like to write a simple program, which can read random line: >( file.txt has 7 lines ) > >1: srand 5269 >2: f = File.new( "file.txt", "r" ) >3: print f.readlines[ rand(6) ] > >Thus I can get one line in file.txt by random. ( of course easily. ) >Still, the "file.txt" will not only be a 7-lines file, right ? ;) >How can I get the number of lines of a file ? >So that I can get one line in file.txt by random >more flexibly just like: > >1: srand 5269 >2: f = File.new( "file.txt", "r" ) >3: print f.readlines[ rand( lines_of_file-1 ) ] > > > this way should work srand 5269 lines = File.readlines("file.txt") print lines[rand(lines.length)] it reads the file into an array and then uses the length of the array HTH -- Mark Sparshatt