17

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?

1
  • 2
    Not what you asked for but you may be interested nonetheless, if you ever wanted all the lines in a file (the one you're actually in) you can add this to your script: p File.new(__FILE__).each.with_index { |l,i| puts "line #{i+1}: #{l}" };''. Try it out. Commented Jul 31, 2016 at 13:35

3 Answers 3

35

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome. Never knew about the with_index method on Enumerable. I learned something today! Thanks much meng!
8

Slightly modifying @sagarpandya82's code:

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

1 Comment

This is clever. Thanks for this modification.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.