2016-07-31 60 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.