Forum: Ruby Regarding File Open

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Be955f2578b8971802ceab589fe24ad3?d=identicon&s=25 Suresh Ilankovan (sureshhey)
on 2016-09-06 02:45
For e.g you go the text file called text.txt
with the following details

Hello world I'm am a nice guys
Hello world I'm am a bad guys

line_count = 0
text = ' '
File.open("text.txt").each do | line |
 line_count = 0
 text << line
end

The above code means it will retrieve the text file
And add beside a line_count +1 right?

Hello world I'm a nice guys  line_count + 1
Hello world I'm a bad guys   line_count + 2

Am I'm correct when explaining this code?
0fa73332c8e4a3b06ea439fd3f034322?d=identicon&s=25 Ronald Fischer (rovf)
on 2016-09-06 12:44
Actually, in the code you supplied, the variable line_count is never
incremented, so it stays zero. BTW, it is not necessary in this case to
explicitly keep track of the line count, because Ruby provides the
global variable $. (dollar-period), which holds the line number of the
last line read.

BTW, the same effect which your code would do, could also be achieved by
a single statement:

    text = ' ' + IO.read('text.txt')
This topic is locked and can not be replied to.