Subclasses: File
Class IO is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream.
Many of the examples in this section use class File, the only standard subclass of IO. The two classes are closely associated.
As used in this section, aPortname may take any of the following forms.
|” indicates a subprocess. The remainder of the string following the “|” is invoked as a process with appropriate input/output channels connected to it.|-” will create another Ruby instance as a subprocess.Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename “/gumby/ruby/test.rb” will be opened as “\gumby\ruby\test.rb”. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"c:\\gumby\\ruby\\test.rb"Our examples here will use the Unix-style forward slashes; File::SEPARATOR can be used to get the platform-specific separator character.
I/O ports may be opened in any one of several different modes, which are shown in this section as aModeString. This mode string must be one of the values listed in Table 22.5.
| Mode | Meaning |
|---|---|
| “r” | Read-only, starts at beginning of file (default mode). |
| “r+” | Read-write, starts at beginning of file. |
| “w” | Write-only, truncates existing file to zero length or creates a new file for writing. |
| “w+” | Read-write, truncates existing file to zero length or creates a new file for reading and writing. |
| “a” | Write-only, starts at end of file if file exists, otherwise creates a new file for writing. |
| “a+” | Read-write, starts at end of file if file exists, otherwise creates a new file for reading and writing. |
| “b” | (DOS/Windows only) Binary file mode (may appear with any of the key letters listed above). |
Enumerablecollect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_anilIO.foreach("testfile") {|x| print "GOT ", x }produces:
GOT This is line one
GOT This is line two
GOT This is line three
GOT And so on...File object (a stream) for the given integer file descriptor and mode string. See also IO#fileno.
a = IO.new(2,"w") # '2' is standard error
$stderr.puts "Hello"
a.puts "World"produces:
Hello
WorldIO objects: [
readFile, writeFile ]. Not available on all
platforms.
In the example below, the two processes close the ends of the
pipe that they are not using. This is not just a cosmetic
nicety. The read end of a pipe will not generate an end of file
condition if there are any writers with the pipe still open. In
the case of the parent process, the rd.read will never
return if it does not first issue a wr.close.
rd, wr = IO.pipe
if fork
wr.close
puts "Parent got: <#{rd.read}>"
rd.close
Process.wait
else
rd.close
puts "Sending message to parent"
wr.write "Hi Dad"
wr.close
endproduces:
Sending message to parent
Parent got: <Hi Dad>nilRuns the specified command string as a subprocess; the subprocess's standard input and output will be connected to the returned IO object. If aCmdString starts with a “-”, then a new instance of Ruby is started as the subprocess. The default mode for the new file object is “r”, but aModeString may be set to any of the modes in Table 22.5.
If a block is given, Ruby will run the command as a child connected to Ruby with a pipe. Ruby's end of the pipe will be passed as a parameter to the block.
If a block is given with a aCmdString of “-”, the block will be run in two separate processes: once in the parent, and once in a child. The parent process will be passed the pipe object as a parameter to the block, the child version of the block will be passed nil, and the child's standard in and standard out will be connected to the parent through the pipe. Not available on all platforms.
f = IO.popen("uname")
p f.readlines
puts "Parent is #{Process.pid}"
IO.popen ("date") { |f| puts f.gets }
IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f}"}produces:
["Linux\n"]
Parent is 561
Sun Jun 9 00:17:46 CDT 2002
564 is here, f is
561 is here, f is #<IO:0x401b54dc>a = IO.readlines("testfile")
a[0] → "This is line one\n"nilKernel#select.to_s.
$stdout << "Hello " << "world!\n"produces:
Hello world!nilIOError is raised if such an attempt is made. I/O streams are automatically closed when they are claimed by the garbage collector. nilIOError if the stream is not duplexed.
f = IO.popen("/bin/sh","r+")
f.close_read
f.readlinesproduces:
prog.rb:3:in `readlines': not opened for reading (IOError)
from prog.rb:3nilIOError if the stream is not duplexed.
f = IO.popen("/bin/sh","r+")
f.close_write
f.print "nowhere"produces:
prog.rb:3:in `write': not opened for writing (IOError)
from prog.rb:3:in `print'
from prog.rb:3true or falsetrue if ios is completely closed (for duplex streams, both reader and writer), false otherwise.
f = File.new("testfile")
f.close → nil
f.closed? → true
f = IO.popen("/bin/sh","r+")
f.close_write → nil
f.closed? → false
f.close_read → nil
f.closed? → trueIOerror will be raised.
f = File.new("testfile")
f.each {|line| puts "#{f.lineno}: #{line}" }produces:
1: This is line one
2: This is line two
3: This is line three
4: And so on...nilIOerror will be raised.
f = File.new("testfile")
checksum = 0
f.each_byte {|x| checksum ^= x } → #<File:0x401b5cac>
checksum → 12IO#each.
true or falseIOError will be raised.
f = File.new("testfile")
dummy = f.readlines
f.eof → truetrue or falseIO#eof.
fcntl(2) for details. Not implemented on all platforms. $stdin.fileno → 0
$stdout.fileno → 1$stdout.print "no newline"
$stdout.flushproduces:
no newlinenilnil if called at end of file.
f = File.new("testfile")
f.getc → 84
f.getc → 104nilnil reads the entire contents, and a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs). The stream must be opened for reading or an IOerror will be raised. The line read in will be returned and also assigned to $_. Returns nil if called at end of file.
File.new("testfile").gets → "This is line one\n"
$_ → "This is line one\n"ioctl(2) for details. Not implemented on all platforms. true or falsetrue if ios is associated with a
terminal device (tty), false otherwise.
File.new("testfile").isatty → false
File.new("/dev/tty").isatty → truelineno counts the number of times gets is called, rather than the number of newlines encountered. The two values will differ if gets is called with a separator other than newline. See also the $. variable.
f = File.new("testfile")
f.lineno → 0
f.gets → "This is line one\n"
f.lineno → 1
f.gets → "This is line two\n"
f.lineno → 2f = File.new("testfile")
f.gets → "This is line one\n"
$. → 1
f.lineno = 1000
f.lineno → 1000
$. # lineno of last read → 1
f.gets → "This is line two\n"
$. # lineno of last read → 1001IO.popen.
pipe = IO.popen("-")
if pipe
$stderr.puts "In parent, child pid is #{pipe.pid}"
else
$stderr.puts "In child, pid is #{$$}"
endproduces:
In parent, child pid is 600In child, pid is 600
f = File.new("testfile")
f.pos → 0
f.gets → "This is line one\n"
f.pos → 17f = File.new("testfile")
f.pos = 17
f.gets → "This is line two\n"nilnil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method. Returns nil.
$stdout.print("This is ", 100, " percent.\n")produces:
This is 100 percent.nilKernel#sprintf for details.String or a Fixnum) on ios.
$stdout.putc "A"
$stdout.putc 65produces:
AAnilIO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.
$stdout.puts("this", "is", "a", "test")produces:
this
is
a
testnilnil if called at end of file.
f = File.new("testfile")
f.read(16) → "This is line one"IO#getc, but raises an EOFError
on end of file.
IO#gets, but raises an EOFError
on end of file.
IOerror will be raised.
f = File.new("testfile")
f.readlines[0] → "This is line one\n"f1 = File.new("testfile")
f2 = File.new("testfile")
f2.readlines[0] → "This is line one\n"
f2.reopen(f1) → #<File:0x401b5a54>
f2.readlines[0] → "This is line one\n"lineno to zero.
f = File.new("testfile")
f.readline → "This is line one\n"
f.rewind → 0
f.lineno → 0
f.readline → "This is line one\n"SEEK_SET ) → 0IO::SEEK_CUR |
Seeks to anInteger plus current position. |
IO::SEEK_END |
Seeks to anInteger plus end of stream (you probably want a negative value for anInteger). |
IO::SEEK_SET |
Seeks to the absolute location given by anInteger. |
f = File.new("testfile")
f.seek(-13, IO::SEEK_END) → 0
f.readline → "And so on...\n"File::Stat.
f = File.new("testfile")
s = f.stat
"%o" % s.mode → "100644"
s.blksize → 4096
s.atime → Sun Jun 09 00:17:48 CDT 2002true or falsef = File.new("testfile")
f.sync → falsetrue or false. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered internally. Returns the new state.
f = File.new("testfile")
f.sync = trueSystemCallError on error and EOFError at end of file.
f = File.new("testfile")
f.sysread(16) → "This is line one"SystemCallError on error.
f = File.new("out", "w")
f.syswrite("ABCDEF") → 6IO#pos. IO#fileno. true or falseIO#isatty. nilIO#sysread).
f = File.new("testfile") → #<File:0x401b5b80>
c = f.getc → 84
f.ungetc(c) → nil
f.getc → 84to_s. Returns the number of bytes written.
count = $stdout.write( "This is a test\n" )
puts "That was #{count} bytes of data"produces:
This is a test
That was 15 bytes of dataExtracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).
Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.