簡體   English   中英

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

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

如果我在c1有一個字符串,我可以通過執行以下操作將其打印出來:

c1.each_line do |line|
  puts line
end

我想用每行給出每行的編號,如下所示:

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

但這不適用於字符串。

我試過用$. 當我在上面的迭代器中這樣做時:

puts #{$.} #{line}

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

我也試過使用lineno ,但這似乎只在我加載文件時有效,而不是在我使用字符串時。

如何打印或訪問字符串上每行的行號?

稍微修改您的代碼,試試這個:

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

這與Enumerable中的with_index方法一起使用。

略微修改@ sagarpandya82的代碼:

c1.each_line.with_index(1) do |line, index|
  puts "line: #{index}: #{line}"
end
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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM