marcamillion
marcamillion

Reputation: 33755

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

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?

Upvotes: 17

Views: 6601

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110685

c1 = "Hey diddle diddle,\nthe cat and the fiddle,\nthe cow jumped\nover the moon.\n"

n = 1.step
  #=> #<Enumerator: 1:step> 
c1.each_line { |line| puts "line: #{n.next}: #{line}" }
  # line: 1: Hey diddle diddle,
  # line: 2: the cat and the fiddle,
  # line: 3: the cow jumped
  # line: 4: over the moon.

Upvotes: 3

Sagar Pandya
Sagar Pandya

Reputation: 9497

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.

Upvotes: 35

Aetherus
Aetherus

Reputation: 8888

Slightly modifying @sagarpandya82's code:

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

Upvotes: 8

Related Questions