Returns true if the database is closed, false otherwise.
Returns a new array consisting of the [key, value] pairs for which the code block returns true.
Returns true if the database is empty, false otherwise.
Deletes all data from the database.
Returns a Hash
(not a DBM
database) created by using each value in the database as a key, with the corresponding key as its value.
Returns true if the database contains the specified key, false otherwise.
Yields each member value from the struct to the block and returns an Array
containing the member values from the struct
for which the given block returns a true value (equivalent to Enumerable#select
).
Lots = Struct.new(:a, :b, :c, :d, :e, :f) l = Lots.new(11, 22, 33, 44, 55, 66) l.select {|v| v.even? } #=> [22, 44, 66]
Struct#filter
is an alias for Struct#select
.
Yields each member value from the struct to the block and returns an Array
containing the member values from the struct
for which the given block returns a true value (equivalent to Enumerable#select
).
Lots = Struct.new(:a, :b, :c, :d, :e, :f) l = Lots.new(11, 22, 33, 44, 55, 66) l.select {|v| v.even? } #=> [22, 44, 66]
Struct#filter
is an alias for Struct#select
.
Flushes input and output buffers in kernel.
You must require ‘io/console’ to use this method.
Reads and returns a line without echo back. Prints prompt
unless it is nil
.
You must require ‘io/console’ to use this method.
Returns an File
instance opened console.
If sym
is given, it will be sent to the opened console with args
and the result will be returned instead of the console IO
itself.
You must require ‘io/console’ to use this method.
Returns true
if an IO
object is in non-blocking mode.
Enables non-blocking mode on a stream when set to true
, and blocking mode when set to false
.
Yields self
in non-blocking mode.
When false
is given as an argument, self
is yielded in blocking mode. The original mode is restored after the block is executed.
With no associated block, IO.open
is a synonym for IO.new
. If the optional code block is given, it will be passed io
as an argument, and the IO
object will automatically be closed when the block terminates. In this instance, IO.open
returns the value of the block.
See IO.new
for a description of the fd
, mode
and opt
parameters.
Opens the given path, returning the underlying file descriptor as a Integer
.
IO.sysopen("testfile") #=> 3
Runs the specified command as a subprocess; the subprocess’s standard input and output will be connected to the returned IO
object.
The PID of the started process can be obtained by IO#pid
method.
cmd is a string or an array as follows.
cmd: "-" : fork commandline : command line string which is passed to a shell [env, cmdname, arg1, ..., opts] : command name and zero or more arguments (no shell) [env, [cmdname, argv0], arg1, ..., opts] : command name, argv[0] and zero or more arguments (no shell) (env and opts are optional.)
If cmd is a String
“-
”, then a new instance of Ruby is started as the subprocess.
If cmd is an Array
of String
, then it will be used as the subprocess’s argv
bypassing a shell. The array can contain a hash at first for environments and a hash at last for options similar to spawn
.
The default mode for the new file object is “r”, but mode may be set to any of the modes listed in the description for class IO
. The last argument opt qualifies mode.
# set IO encoding IO.popen("nkf -e filename", :external_encoding=>"EUC-JP") {|nkf_io| euc_jp_string = nkf_io.read } # merge standard output and standard error using # spawn option. See the document of Kernel.spawn. IO.popen(["ls", "/", :err=>[:child, :out]]) {|ls_io| ls_result_with_error = ls_io.read } # spawn options can be mixed with IO options IO.popen(["ls", "/"], :err=>[:child, :out]) {|ls_io| ls_result_with_error = ls_io.read }
Raises exceptions which IO.pipe
and Kernel.spawn
raise.
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. At the end of block, Ruby closes the pipe and sets $?
. In this case IO.popen
returns the value of the block.
If a block is given with a cmd 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 f.close puts "Parent is #{Process.pid}" IO.popen("date") {|f| puts f.gets } IO.popen("-") {|f| $stderr.puts "#{Process.pid} is here, f is #{f.inspect}"} p $? IO.popen(%w"sed -e s|^|<foo>| -e s&$&;zot;&", "r+") {|f| f.puts "bar"; f.close_write; puts f.gets }
produces:
["Linux\n"] Parent is 21346 Thu Jan 15 22:41:19 JST 2009 21346 is here, f is #<IO:fd 3> 21352 is here, f is nil #<Process::Status: pid 21352 exit 0> <foo>bar;zot;
Calls select(2) system call. It monitors given arrays of IO
objects, waits until one or more of IO
objects are ready for reading, are ready for writing, and have pending exceptions respectively, and returns an array that contains arrays of those IO
objects. It will return nil
if optional timeout value is given and no IO
object is ready in timeout seconds.
IO.select
peeks the buffer of IO
objects for testing readability. If the IO
buffer is not empty, IO.select
immediately notifies readability. This “peek” only happens for IO
objects. It does not happen for IO-like objects such as OpenSSL::SSL::SSLSocket
.
The best way to use IO.select
is invoking it after nonblocking methods such as read_nonblock
, write_nonblock
, etc. The methods raise an exception which is extended by IO::WaitReadable
or IO::WaitWritable
. The modules notify how the caller should wait with IO.select
. If IO::WaitReadable
is raised, the caller should wait for reading. If IO::WaitWritable
is raised, the caller should wait for writing.
So, blocking read (readpartial
) can be emulated using read_nonblock
and IO.select
as follows:
begin result = io_like.read_nonblock(maxlen) rescue IO::WaitReadable IO.select([io_like]) retry rescue IO::WaitWritable IO.select(nil, [io_like]) retry end
Especially, the combination of nonblocking methods and IO.select
is preferred for IO
like objects such as OpenSSL::SSL::SSLSocket
. It has to_io
method to return underlying IO
object. IO.select
calls to_io
to obtain the file descriptor to wait.
This means that readability notified by IO.select
doesn’t mean readability from OpenSSL::SSL::SSLSocket
object.
The most likely situation is that OpenSSL::SSL::SSLSocket
buffers some data. IO.select
doesn’t see the buffer. So IO.select
can block when OpenSSL::SSL::SSLSocket#readpartial
doesn’t block.
However, several more complicated situations exist.
SSL is a protocol which is sequence of records. The record consists of multiple bytes. So, the remote side of SSL sends a partial record, IO.select
notifies readability but OpenSSL::SSL::SSLSocket
cannot decrypt a byte and OpenSSL::SSL::SSLSocket#readpartial
will block.
Also, the remote side can request SSL renegotiation which forces the local SSL engine to write some data. This means OpenSSL::SSL::SSLSocket#readpartial
may invoke write
system call and it can block. In such a situation, OpenSSL::SSL::SSLSocket#read_nonblock
raises IO::WaitWritable
instead of blocking. So, the caller should wait for ready for writability as above example.
The combination of nonblocking methods and IO.select
is also useful for streams such as tty, pipe socket socket when multiple processes read from a stream.
Finally, Linux kernel developers don’t guarantee that readability of select(2) means readability of following read(2) even for a single process. See select(2) manual on GNU/Linux system.
Invoking IO.select
before IO#readpartial
works well as usual. However it is not the best way to use IO.select
.
The writability notified by select(2) doesn’t show how many bytes are writable. IO#write
method blocks until given whole string is written. So, IO#write(two or more bytes)
can block after writability is notified by IO.select
. IO#write_nonblock
is required to avoid the blocking.
Blocking write (write
) can be emulated using write_nonblock
and IO.select
as follows: IO::WaitReadable
should also be rescued for SSL renegotiation in OpenSSL::SSL::SSLSocket
.
while 0 < string.bytesize begin written = io_like.write_nonblock(string) rescue IO::WaitReadable IO.select([io_like]) retry rescue IO::WaitWritable IO.select(nil, [io_like]) retry end string = string.byteslice(written..-1) end
an array of IO
objects that wait until ready for read
an array of IO
objects that wait until ready for write
an array of IO
objects that wait for exceptions
a numeric value in second
rp, wp = IO.pipe mesg = "ping " 100.times { # IO.select follows IO#read. Not the best way to use IO.select. rs, ws, = IO.select([rp], [wp]) if r = rs[0] ret = r.read(5) print ret case ret when /ping/ mesg = "pong\n" when /pong/ mesg = "ping " end end if w = ws[0] w.write(mesg) end }
produces:
ping pong ping pong ping pong (snipped) ping
Reassociates ios with the I/O stream given in other_IO or to a new stream opened on path. This may dynamically change the actual class of this stream. The mode
and opt
parameters accept the same values as IO.open
.
f1 = File.new("testfile") f2 = File.new("testfile") f2.readlines[0] #=> "This is line one\n" f2.reopen(f1) #=> #<File:testfile> f2.readlines[0] #=> "This is line one\n"
Reads a one-character string from ios. Raises an EOFError
on end of file.
f = File.new("testfile") f.readchar #=> "h" f.readchar #=> "e"
Seeks to a given offset anInteger in the stream according to the value of whence:
:CUR or IO::SEEK_CUR | Seeks to _amount_ plus current position ----------------------+-------------------------------------------------- :END or IO::SEEK_END | Seeks to _amount_ plus end of stream (you | probably want a negative value for _amount_) ----------------------+-------------------------------------------------- :SET or IO::SEEK_SET | Seeks to the absolute location given by _amount_
Example:
f = File.new("testfile") f.seek(-13, IO::SEEK_END) #=> 0 f.readline #=> "And so on...\n"
Closes ios and flushes any pending writes to the operating system. The stream is unavailable for any further data operations; an IOError
is raised if such an attempt is made. I/O streams are automatically closed when they are claimed by the garbage collector.
If ios is opened by IO.popen
, close
sets $?
.
Calling this method on closed IO
object is just ignored since Ruby 2.3.