如何打印字符串中每行的行号?

mar*_*ion 13 ruby string

如果我有一个字符串c1,我可以通过执行以下操作将其打印出来:

c1.each_line do |line|
  puts line
end
Run Code Online (Sandbox Code Playgroud)

我想用每行给出每行的编号,如下所示:

c1.each_with_index  do |line, index|
  puts "#{index} #{line}"
end
Run Code Online (Sandbox Code Playgroud)

但这不适用于字符串.

我试过用$..当我在上面的迭代器中这样做时:

puts #{$.} #{line}
Run Code Online (Sandbox Code Playgroud)

它打印每行最后一行的行号.

我也试过使用lineno,但这似乎只在我加载文件时起作用,而不是在我使用字符串时.

如何打印或访问字符串上每行的行号?

Sag*_*dya 24

稍微修改您的代码,试试这个:

c1.each_line.with_index do |line, index|
   puts "line: #{index+1}: #{line}"
end
Run Code Online (Sandbox Code Playgroud)

这与with_indexEnumerable中的方法一起使用.

  • 这太棒了。从来不知道Enumerable的`with_index`方法。我今天学到了一些东西!非常感谢孟! (2认同)

Aet*_*rus 7

稍微修改@ sagarpandya82的代码:

c1.each_line.with_index(1) do |line, index|
  puts "line: #{index}: #{line}"
end
Run Code Online (Sandbox Code Playgroud)