An IO object represents a readable or writable connection to a file, keyboard, screen, or other device. Ruby programs interact with these streams by sending messages to objects; the IO class wraps system-level input and output operations. section 12.1 section 12.1.1
The standard streams are IO objects available when a Ruby program starts:
- STDIN provides standard input; STDOUT and STDERR provide standard output and error output. section 12.1.1
- puts adds a newline, while print and write do not. puts and print return nil; write returns the number of bytes written. section 12.1.1
Sending puts or write to STDERR writes to that stream; write returns the number of bytes written. section 12.1.1
IO objects are enumerable: each reads records from the stream, using the global input record separator, $/, to determine where each record ends. Changing $/ changes how input is grouped, and enumerable methods such as select and map can operate on the records. section 12.1.2
>> STDIN.each {|line| p line }
This is line 1
"This is line 1\n"
This is line 2
"This is line 2\n"
All separated by $/, which is a newline character
"All separated by $/, which is a newline character\n"
With the default newline separator, STDIN.each reads and prints one line per iteration. section 12.1.2
File inherits from IO, so File objects support IO methods. Opening a file in write mode creates it or overwrites its contents; append mode creates it if needed and adds new data at the end. section 12.2.6 section 12.6
>> f = File.new("data.out", "w")
=> #<File:data.out>
>> f.puts "David A. Black, Rubyist"
=> nil
>> f.close
=> nil
>> puts File.read("data.out")
David A. Black, Rubyist
=> nil
>> f = File.new("data.out", "a")
=> #<File:data.out>
>> f.puts "Joe Leo III, Rubyist"
=> nil
>> f.close
=> nil
>> puts File.read("data.out")
David A. Black, Rubyist
Joe Leo III, Rubyist
The example writes a line to a file, then appends another and reads back the resulting contents. section 12.2.6





