Read a specific line from a file: Difference between revisions

→‎{{header|Ruby}}: replaced completely using newer methods.
(→‎{{header|Ruby}}: replaced completely using newer methods.)
Line 1,024:
 
=={{header|Ruby}}==
The each_line method returns an Enumerator, so no more than seven lines are read.
<lang ruby>def getNthLine(filename, n)
<lang ruby> seventh_line = open("/etc/passwd").each_line.take(7).last
line=""
</lang>
File.open(filename) do |f|
n.times do |nr|
line = f.gets
if line.nil?
puts "file #{filename} does not have #{n} lines, only #{nr}"
break
end
end
end
line
end
 
puts getNthLine("/etc/passwd", 7)</lang>
 
=={{header|Run BASIC}}==
1,149

edits