Regarding File Open

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?

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs