Search code examples
rubylearn-ruby-the-hard-way

Texts in a file not printing properly


Working through this problem and I have typed out the code EXACTLY like the problem states - even tried to copy and paste to see if it was something I was doing wrong but its not.

The code that I have is at the bottom of this post. I am sending the argument 'test.txt' which contains:

This is stuff I typed into a file. 
It is really cool stuff. 
Lots and lots of fun to have in here

however, when i run the code, during the print_all(current_file) it ONLY prints 'lots and lots of fun to have here.' - which is the last line of the file.

And where it is supposed to print out each individual line, it prints:

1 ["This is stuff I typed into a file. \rIt is really cool stuff. \rLots and lots of fun to have in here.\r\r"]
2 []
3 []'

essentially capturing all lines as 1 line, and printing nothing where its supposed to print line 2 and 3.

Any ideas?

input_file = ARGV[0]

def print_all(f)
  puts f.read()
end

def rewind(f)
  f.seek(0, IO::SEEK_SET)
end

def print_a_line(line_count, f)
  puts "#{line_count} #{f.readlines()}"
end

current_file = File.open(input_file)

puts "First let's print the whole file:"
puts # a blank line

print_all(current_file)

puts "Now let's rewind, kind of like a tape."

rewind(current_file)

puts "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

Solution

  • EDIT: It looks like the test file you are using only contains the character \r to indicate a newline, instead of the windows \r\n or the linux \n. Your text editor may interpret \r as a newline, but ruby doesn't.

    Original answer:

    As for you first problem with print_all, I couldn't reproduce it. How do you run the script?

    In the second problem, you are using the method file.readlines() (note the final s) instead of file.readline().

    file.readlines() reads the entire file and returns its content in an array, with each line as an element of the array. This is why you get your whole file in the first call. Subsequent calls return the empty array because you are the end of the file (you'd need to "rewind" as you did previously to continue reading from the file).

    file.readline() reads one line of the file and returns its content as a string, which is probably what you want.

    I linked to the ruby documentation for further reads (no pun intended) about the question. Note that the relevant methods are detailed in the documentation for the IO class, since File inherits from this class and the readlines/readline methods are inherited from IO.