notsoscottishscot
notsoscottishscot

Reputation: 368

Ruby - Read file and print line number

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

Upvotes: 5

Views: 4233

Answers (2)

dawg
dawg

Reputation: 103844

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...

Upvotes: 6

Sebastián Palma
Sebastián Palma

Reputation: 33420

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

Upvotes: 3

Related Questions