marcamillion marcamillion - 2 months ago 11x
Ruby Question

How do I print the line number of each line in a String?

If I have a string in my varaible

, I can easily print it out in a line format by doing the following:

c1.each_line do |line|
puts line

However, that doesn't give me the number of each line with each line.

Based on my research, I can only find two ways to do this. Either using
, however when I do that in the above iterator like so (
puts #{$.} #{line}
, all that happens is it prints the line number for the last line on each line.

I have also tried using
, but that seems to only work when I am loading in a file not when I am using a very long string.

So how do I print/access the line number for each line on a String in Ruby?

Ideally, what I would love to be able to do is simply something like this:

c1.each_with_index do |line, index|
puts "#{index} #{line}"

But that doesn't work on a string.


Slightly modifying your code, try this:

c1.each_line.with_index do |line, index|
   puts "line: #{index+1}: #{line}"

This uses with with_index method in Enumerable.