This isn't going to be easy to explain and I haven't found any answers for it.
I want to be able to read .txt file in Ruby and somehow be able to print the line number.
Example:
#file.txt:
#Hello
#My name is John Smith
#How are you?
File.open("file.txt").each do |line|
puts line
puts line.linenumber
end
#First Iteration outputs
#=> Hello
#=> 1
#Second Iteration outputs
#=> My name is John Smith
#=> 2
#Third Iteration outputs
#=> How are you?
#=> 3
I hope this makes sense and I hope it's easily possible.
Thanks in advance, Reece
You can use Enumerable#each_with_index
:
Calls block with two arguments, the item and its index, for each item in enum. Given arguments are passed through to each().
File.open(filename).each_with_index do |line, index|
p "#{index} #{line}"
end
Ruby, like Perl, has the special variable $.
which contains the line number of a file.
File.open("file.txt").each do |line|
puts line, $.
end
Prints:
#Hello
1
#My name is John Smith
2
#How are you?
3
Strip the \\n
from line
if you want the number on the same line:
File.open("file.txt").each do |line|
puts "#{line.rstrip} #{$.}"
end
#Hello 1
#My name is John Smith 2
#How are you? 3
As stated in comments, rather than use File.open
you can use File.foreach with the benefit of autoclose at the end of the block:
File.foreach('file.txt') do |line|
puts line, $.
end
# same output...
## Like in PHP ## To get line number __LINE__ ## To get file name __FILE__
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.