Returns the integer month of the year for self
, in range (1..12):
t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006 t.mon # => 1
Returns the integer year for self
:
t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006 t.year # => 2000
Returns the string name of the time zone for self
:
Time.utc(2000, 1, 1).zone # => "UTC" Time.new(2000, 1, 1).zone # => "Central Standard Time"
Returns true
if self
represents a Monday, false
otherwise:
t = Time.utc(2000, 1, 3) # => 2000-01-03 00:00:00 UTC t.monday? # => true
Related: Time#tuesday?
, Time#wednesday?
, Time#thursday?
.
Returns true
if self
represents a Thursday, false
otherwise:
t = Time.utc(2000, 1, 6) # => 2000-01-06 00:00:00 UTC t.thursday? # => true
Related: Time#friday?
, Time#saturday?
, Time#sunday?
.
Returns the number of microseconds in the subseconds part of self
in the range (0..999_999); lower-order digits are truncated, not rounded:
t = Time.now # => 2022-07-11 14:59:47.5484697 -0500 t.usec # => 548469
Related: Time#subsec
(returns exact subseconds).
Returns the number of nanoseconds in the subseconds part of self
in the range (0..999_999_999); lower-order digits are truncated, not rounded:
t = Time.now # => 2022-07-11 15:04:53.3219637 -0500 t.nsec # => 321963700
Related: Time#subsec
(returns exact subseconds).
Returns the exact subseconds for self
as a Numeric
(Integer
or Rational
):
t = Time.now # => 2022-07-11 15:11:36.8490302 -0500 t.subsec # => (4245151/5000000)
If the subseconds is zero, returns integer zero:
t = Time.new(2000, 1, 1, 2, 3, 4) # => 2000-01-01 02:03:04 -0600 t.subsec # => 0
Returns a string representation of self
, formatted according to the given string format
. See Formats for Dates and Times.
Like Time.utc
, except that the returned Time
object has the local timezone, not the UTC timezone:
# With seven arguments. Time.local(0, 1, 2, 3, 4, 5, 6) # => 0000-01-02 03:04:05.000006 -0600 # With exactly ten arguments. Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) # => 0005-04-03 02:01:00 -0600
Flushes input and output buffers in kernel.
You must require ‘io/console’ to use this method.
Returns the current cursor position as a two-element array of integers (row, column)
io.cursor # => [3, 5]
You must require ‘io/console’ to use this method.
Returns true
if key
is pressed. key
may be a virtual key code or its name (String
or Symbol
) with out “VK_” prefix.
This method is Windows only.
You must require ‘io/console’ to use this method.
Reads and returns a line without echo back. Prints prompt
unless it is nil
.
The newline character that terminates the read line is removed from the returned string, see String#chomp!
.
You must require ‘io/console’ to use this method.
require 'io/console' IO::console.getpass("Enter password:") Enter password: # => "mypassword"
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
.
This method set or clear O_NONBLOCK flag for the file descriptor in ios.
The behavior of most IO
methods is not affected by this flag because they retry system calls to complete their task after EAGAIN and partial read/write. (An exception is IO#syswrite
which doesn’t retry.)
This method can be used to clear non-blocking mode of standard I/O. Since nonblocking methods (read_nonblock
, etc.) set non-blocking mode but they doesn’t clear it, this method is usable as follows.
END { STDOUT.nonblock = false } STDOUT.write_nonblock("foo")
Since the flag is shared across processes and many non-Ruby commands doesn’t expect standard I/O with non-blocking mode, it would be safe to clear the flag before Ruby program exits.
For example following Ruby program leaves STDIN/STDOUT/STDER non-blocking mode. (STDIN, STDOUT and STDERR are connected to a terminal. So making one of them nonblocking-mode effects other two.) Thus cat command try to read from standard input and it causes “Resource temporarily unavailable” error (EAGAIN).
% ruby -e ' STDOUT.write_nonblock("foo\n")'; cat foo cat: -: Resource temporarily unavailable
Clearing the flag makes the behavior of cat command normal. (cat command waits input from standard input.)
% ruby -rio/nonblock -e ' END { STDOUT.nonblock = false } STDOUT.write_nonblock("foo") '; cat foo
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.
Creates a new IO object, via IO.new
with the given arguments.
With no block given, returns the IO object.
With a block given, calls the block with the IO object and returns the block’s value.
Opens the file at the given path with the given mode and permissions; returns the integer file descriptor.
If the file is to be readable, it must exist; if the file is to be writable and does not exist, it is created with the given permissions:
File.write('t.tmp', '') # => 0 IO.sysopen('t.tmp') # => 8 IO.sysopen('t.tmp', 'w') # => 9
Executes the given command cmd
as a subprocess whose $stdin and $stdout are connected to a new stream io
.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
If no block is given, returns the new stream, which depending on given mode
may be open for reading, writing, or both. The stream should be explicitly closed (eventually) to avoid resource leaks.
If a block is given, the stream is passed to the block (again, open for reading, writing, or both); when the block exits, the stream is closed, and the block’s value is assigned to global variable $?
and returned.
Optional argument mode
may be any valid IO mode. See Access Modes.
Required argument cmd
determines which of the following occurs:
The process forks.
A specified program runs in a shell.
A specified program runs with specified arguments.
A specified program runs with specified arguments and a specified argv0
.
Each of these is detailed below.
The optional hash argument env
specifies name/value pairs that are to be added to the environment variables for the subprocess:
IO.popen({'FOO' => 'bar'}, 'ruby', 'r+') do |pipe| pipe.puts 'puts ENV["FOO"]' pipe.close_write pipe.gets end => "bar\n"
Optional keyword arguments opts
specify:
Encoding options.
Options for Kernel#spawn
.
Forked Process
When argument cmd
is the 1-character string '-'
, causes the process to fork:
IO.popen('-') do |pipe| if pipe $stderr.puts "In parent, child pid is #{pipe.pid}\n" else $stderr.puts "In child, pid is #{$$}\n" end end
Output:
In parent, child pid is 26253 In child, pid is 26253
Note that this is not supported on all platforms.
Shell Subprocess
When argument cmd
is a single string (but not '-'
), the program named cmd
is run as a shell command:
IO.popen('uname') do |pipe| pipe.readlines end
Output:
["Linux\n"]
Another example:
IO.popen('/bin/sh', 'r+') do |pipe| pipe.puts('ls') pipe.close_write $stderr.puts pipe.readlines.size end
Output:
213
Program Subprocess
When argument cmd
is an array of strings, the program named cmd[0]
is run with all elements of cmd
as its arguments:
IO.popen(['du', '..', '.']) do |pipe| $stderr.puts pipe.readlines.size end
Output:
1111
Program Subprocess with argv0
When argument cmd
is an array whose first element is a 2-element string array and whose remaining elements (if any) are strings:
cmd[0][0]
(the first string in the nested array) is the name of a program that is run.
cmd[0][1]
(the second string in the nested array) is set as the program’s argv[0]
.
cmd[1..-1]
(the strings in the outer array) are the program’s arguments.
Example (sets $0
to ‘foo’):
IO.popen([['/bin/sh', 'foo'], '-c', 'echo $0']).read # => "foo\n"
Some Special Examples
# 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 Kernel#spawn option. See Kernel#spawn. IO.popen(["ls", "/", :err=>[:child, :out]]) do |io| ls_result_with_error = io.read end # Use mixture of spawn options and IO options. IO.popen(["ls", "/"], :err=>[:child, :out]) do |io| ls_result_with_error = io.read end 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 }
Output (from last section):
["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;
Raises exceptions that IO.pipe
and Kernel.spawn
raise.
Invokes system call select(2), which monitors multiple file descriptors, waiting until one or more of the file descriptors becomes ready for some class of I/O operation.
Not implemented on all platforms.
Each of the arguments read_ios
, write_ios
, and error_ios
is an array of IO
objects.
Argument timeout
is a numeric value (such as integer or float) timeout interval in seconds.
The method monitors the IO objects given in all three arrays, waiting for some to be ready; returns a 3-element array whose elements are:
An array of the objects in read_ios
that are ready for reading.
An array of the objects in write_ios
that are ready for writing.
An array of the objects in error_ios
have pending exceptions.
If no object becomes ready within the given timeout
, nil
is returned.
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 non-blocking 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 non-blocking 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 non-blocking 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)
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
Example:
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 }
Output:
ping pong ping pong ping pong (snipped) ping
Reassociates the stream with another stream, which may be of a different class. This method may be used to redirect an existing stream to a new destination.
With argument other_io
given, reassociates with that stream:
# Redirect $stdin from a file. f = File.open('t.txt') $stdin.reopen(f) f.close # Redirect $stdout to a file. f = File.open('t.tmp', 'w') $stdout.reopen(f) f.close
With argument path
given, reassociates with a new stream to that file path:
$stdin.reopen('t.txt') $stdout.reopen('t.tmp', 'w')
Optional keyword arguments opts
specify:
Encoding options.
Get the internal timeout duration or nil if it was not set.