Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

ruby

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?

like image 576
marcamillion Avatar asked Jul 31 '16 12:07

marcamillion


People also ask

How do you show the line number in a string in python?

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.

How do you show the line number in a string in Linux?

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.


2 Answers

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.

like image 120
Sagar Pandya Avatar answered Oct 18 '22 16:10

Sagar Pandya


Slightly modifying @sagarpandya82's code:

c1.each_line.with_index(1) do |line, index|
  puts "line: #{index}: #{line}"
end
like image 44
Aetherus Avatar answered Oct 18 '22 16:10

Aetherus