Files in Ruby
Writing, rewinding and reading a file line by line.
require "tempfile"
file = Tempfile.new(["notes", ".txt"])
file.write("line one\nline two\nline three\n")
file.rewind
file.each_line { |line| puts line.chomp.upcase }
file.rewind
puts file.read.lines.count
file.close
file.unlink
How it works
Tempfile.newcreates a real file that cleans up after itself.each_linestreams the file;chompdrops the newlines.rewindresets the cursor so the file reads again from the top.
Keywords and builtins used here
putsrequire
The run, in numbers
- Lines
- 13
- Characters to type
- 231
- Tokens
- 67
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 47 seconds.
Step 1 of 3 in Files & errors, step 25 of 29 in Language basics.