2016-07-31 67 views
4

如果我有内c1一个字符串,我可以在一条线上做打印:如何在字符串中打印每行的行号?

c1.each_line do |line| 
    puts line 
end 

我想给每行的数每行是这样的:

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

但这对字符串不起作用。

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

puts #{$.} #{line} 

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

我也尝试使用lineno,但似乎只有当我加载文件时,而不是当我使用字符串。

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

+2

不是你问什么,但你可能会感兴趣尽管如此,如果你想在一个文件中的所有行(第一个你实际上是)你可以将它添加到脚本中:'p File.new(__ FILE __)。each.with_index {| l,i |放置“行#{i + 1}:#{l}”};'''。试试看。 –

回答

7

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

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

它使用与可枚举with_index方法。

+0

这太棒了。从来不知道Enumerable上的'with_index'方法。我今天学到了东西!非常感谢! – marcamillion

3

稍微修改@ sagarpandya82代码:

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

这很聪明。感谢您的修改。 – marcamillion

3
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.