If I have a string within c1
, I can print it in a line by doing:
c1.each_line do |line|
puts line
end
I want to give the number of each line with each line like this:
c1.each_with_index do |line, index|
puts "#{index} #{line}"
end
But that doesn't work on a string.
I tried using $.
. When I do that in the above iterator like so:
puts #{$.} #{line}
it prints the line number for the last line on each line.
I also tried using lineno
, but that seems to work only when I load a file, and not when I use a string.
How do I print or access the line number for each line on a string?
Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.
Show Line NumbersThe -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.
Slightly modifying your code, try this:
c1.each_line.with_index do |line, index|
puts "line: #{index+1}: #{line}"
end
This uses with with_index
method in Enumerable.
Slightly modifying @sagarpandya82's code:
c1.each_line.with_index(1) do |line, index|
puts "line: #{index}: #{line}"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With