What is the Fastest way to get first line and ith line in a file?
···
--
Posted via http://www.ruby-forum.com/.
What is the Fastest way to get first line and ith line in a file?
--
Posted via http://www.ruby-forum.com/.
Hi,
The first line would be
File.foreach('path/to/your/file').first
For getting the n-th line there are several ways, depending on how big
the file is. If the file isn't too big, you may read all lines and then
select the n-th one:
File.readlines('path/to/your/file')[n]
Otherwise I guess you'll have to loop over the lines to get the n-th
one:
result_line = nil
File.foreach('path/to/your/file').with_index do |line, index|
if index == n
result_line = line
break
end
end
Or a bit more compact:
result_line, =
File.foreach('path/to/your/file').with_index.find do |line, index|
index == n
end
The comma after result_line is necessary to drop the index.
--
Posted via http://www.ruby-forum.com/.
File.foreach('path/to/your/file').first
What if I use:
line = FasterCSV.foreach(filename).first
giving the error:
Uncaught exception: no block given
--
Posted via http://www.ruby-forum.com/\.
This should work:
line = FasterCSV.to_enum(:foreach, filename).first
Kind regards
robert
On Mon, Aug 13, 2012 at 11:49 AM, ajay paswan <lists@ruby-forum.com> wrote:
File.foreach('path/to/your/file').first
What if I use:
line = FasterCSV.foreach(filename).first
giving the error:
Uncaught exception: no block given
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/