Sets default external encoding. You should not set Encoding::default_external
in ruby code as strings created before changing the value may have a different encoding from strings created after the value was changed., instead you should use ruby -E
to invoke ruby with the correct default_external.
See Encoding::default_external
for information on how the default external encoding is used.
Returns default internal encoding. Strings will be transcoded to the default internal encoding in the following places if the default internal encoding is not nil:
File
data read from disk
Strings returned from Readline
Strings returned from SDBM
Values from ENV
Values in ARGV including $PROGRAM_NAME
Additionally String#encode
and String#encode!
use the default internal encoding if no encoding is given.
The script encoding (__ENCODING__), not default_internal
, is used as the encoding of created strings.
Encoding::default_internal
is initialized with -E option or nil otherwise.
Sets default internal encoding or removes default internal encoding when passed nil. You should not set Encoding::default_internal
in ruby code as strings created before changing the value may have a different encoding from strings created after the change. Instead you should use ruby -E
to invoke ruby with the correct default_internal.
See Encoding::default_internal
for information on how the default internal encoding is used.
Returns the locale charmap name. It returns nil if no appropriate information.
Debian GNU/Linux LANG=C Encoding.locale_charmap #=> "ANSI_X3.4-1968" LANG=ja_JP.EUC-JP Encoding.locale_charmap #=> "EUC-JP" SunOS 5 LANG=C Encoding.locale_charmap #=> "646" LANG=ja Encoding.locale_charmap #=> "eucJP"
The result is highly platform dependent. So Encoding.find(Encoding.locale_charmap)
may cause an error. If you need some encoding object even for unknown locale, Encoding.find
(“locale”) can be used.
Processes a string returned by message
.
It may add the class name of the exception to the end of the first line. Also, when highlight
keyword is true, it adds ANSI escape sequences to make the message bold.
If you override this method, it must be tolerant for unknown keyword arguments. All keyword arguments passed to full_message
are delegated to this method.
This method is overridden by did_you_mean and error_highlight to add their information.
A user-defined exception class can also define their own detailed_message
method to add supplemental information. When highlight
is true, it can return a string containing escape sequences, but use widely-supported ones. It is recommended to limit the following codes:
Reset (\e[0m
)
Bold (\e[1m
)
Underline (\e[4m
)
Foreground color except white and black
Red (\e[31m
)
Green (\e[32m
)
Yellow (\e[33m
)
Blue (\e[34m
)
Magenta (\e[35m
)
Cyan (\e[36m
)
Use escape sequences carefully even if highlight
is true. Do not use escape sequences to express essential information; the message should be readable even if all escape sequences are ignored.
Returns formatted string of exception. The returned string is formatted using the same format that Ruby uses when printing an uncaught exceptions to stderr.
If highlight is true
the default error handler will send the messages to a tty.
order must be either of :top
or :bottom
, and places the error message and the innermost backtrace come at the top or the bottom.
The default values of these options depend on $stderr
and its tty?
at the timing of a call.
Returns any backtrace associated with the exception. This method is similar to Exception#backtrace
, but the backtrace is an array of Thread::Backtrace::Location
.
This method is not affected by Exception#set_backtrace()
.
Return a list of the local variable names defined where this NameError
exception was raised.
Internal use only.
Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling “attr
:name” on each name in turn. String
arguments are converted to symbols. Returns an array of defined method names as symbols.
Creates an accessor method to allow assignment to the attribute symbol.id2name
. String
arguments are converted to symbols. Returns an array of defined method names as symbols.
Checks for a constant with the given name in mod. If inherit
is set, the lookup will also search the ancestors (and Object
if mod is a Module
).
The value of the constant is returned if a definition is found, otherwise a NameError
is raised.
Math.const_get(:PI) #=> 3.14159265358979
This method will recursively look up constant names if a namespaced class name is provided. For example:
module Foo; class Bar; end end Object.const_get 'Foo::Bar'
The inherit
flag is respected on each lookup. For example:
module Foo class Bar VAL = 10 end class Baz < Bar; end end Object.const_get 'Foo::Baz::VAL' # => 10 Object.const_get 'Foo::Baz::VAL', false # => NameError
If the argument is not a valid constant name a NameError
will be raised with a warning “wrong constant name”.
Object.const_get 'foobar' #=> NameError: wrong constant name foobar
Create an HTTP header block as a string.
Includes the empty line that ends the header block.
content_type_string
If this form is used, this string is the Content-Type
headers_hash
A Hash
of header values. The following header keys are recognized:
The Content-Type header. Defaults to “text/html”
The charset of the body, appended to the Content-Type header.
A boolean value. If true, prepend protocol string and status code, and date; and sets default values for “server” and “connection” if not explicitly set.
The HTTP status code as a String
, returned as the Status header. The values are:
200 OK
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
304 Not Modified
400 Bad Request
401 Authorization Required
403 Forbidden
404 Not Found
405 Method
Not Allowed
406 Not Acceptable
411 Length Required
412 Precondition Failed
500 Internal Server Error
501 Method
Not Implemented
502 Bad Gateway
506 Variant Also Negotiates
The server software, returned as the Server header.
The connection type, returned as the Connection header (for instance, “close”.
The length of the content that will be sent, returned as the Content-Length header.
The language of the content, returned as the Content-Language header.
The time on which the current content expires, as a Time
object, returned as the Expires header.
A cookie or cookies, returned as one or more Set-Cookie headers. The value can be the literal string of the cookie; a CGI::Cookie
object; an Array
of literal cookie strings or Cookie
objects; or a hash all of whose values are literal cookie strings or Cookie
objects.
These cookies are in addition to the cookies held in the @output_cookies field.
Other headers can also be set; they are appended as key: value.
Examples:
http_header # Content-Type: text/html http_header("text/plain") # Content-Type: text/plain http_header("nph" => true, "status" => "OK", # == "200 OK" # "status" => "200 GOOD", "server" => ENV['SERVER_SOFTWARE'], "connection" => "close", "type" => "text/html", "charset" => "iso-2022-jp", # Content-Type: text/html; charset=iso-2022-jp "length" => 103, "language" => "ja", "expires" => Time.now + 30, "cookie" => [cookie1, cookie2], "my_header1" => "my_value", "my_header2" => "my_value")
This method does not perform charset conversion.
Returns true
if the arguments define a valid commercial date, false
otherwise:
Date.valid_commercial?(2001, 5, 6) # => true Date.valid_commercial?(2001, 5, 8) # => false
See Date.commercial
.
See argument start.
Related: Date.jd
, Date.commercial
.
Attempts to convert object
into an IO object via method to_io
; returns the new IO object if successful, or nil
otherwise:
IO.try_convert(STDOUT) # => #<IO:<STDOUT>> IO.try_convert(ARGF) # => #<IO:<STDIN>> IO.try_convert('STDOUT') # => nil
Closes the stream for reading if open for reading; returns nil
. See Open and Closed Streams.
If the stream was opened by IO.popen
and is also closed for writing, sets global variable $?
(child exit status).
Example:
IO.popen('ruby', 'r+') do |pipe| puts pipe.closed? pipe.close_write puts pipe.closed? pipe.close_read puts $? puts pipe.closed? end
Output:
false false pid 14748 exit 0 true
Related: IO#close
, IO#close_write
, IO#closed?
.
Closes the stream for writing if open for writing; returns nil
. See Open and Closed Streams.
Flushes any buffered writes to the operating system before closing.
If the stream was opened by IO.popen
and is also closed for reading, sets global variable $?
(child exit status).
IO.popen('ruby', 'r+') do |pipe| puts pipe.closed? pipe.close_read puts pipe.closed? pipe.close_write puts $? puts pipe.closed? end
Output:
false false pid 15044 exit 0 true
Related: IO#close
, IO#close_read
, IO#closed?
.
Returns the Encoding
object that represents the encoding of the stream, or nil
if the stream is in write mode and no encoding is specified.
See Encodings.
Returns the Encoding
object that represents the encoding of the internal string, if conversion is specified, or nil
otherwise.
See Encodings.
Reads at most maxlen bytes from ios using the read(2) system call after O_NONBLOCK is set for the underlying file descriptor.
If the optional outbuf argument is present, it must reference a String
, which will receive the data. The outbuf will contain only the received data after the method call even if it is not empty at the beginning.
read_nonblock
just calls the read(2) system call. It causes all errors the read(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc. The caller should care such errors.
If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN, it is extended by IO::WaitReadable
. So IO::WaitReadable
can be used to rescue the exceptions for retrying read_nonblock.
read_nonblock
causes EOFError
on EOF.
On some platforms, such as Windows, non-blocking mode is not supported on IO
objects other than sockets. In such cases, Errno::EBADF will be raised.
If the read byte buffer is not empty, read_nonblock
reads from the buffer like readpartial. In this case, the read(2) system call is not called.
When read_nonblock
raises an exception kind of IO::WaitReadable
, read_nonblock
should not be called until io is readable for avoiding busy loop. This can be done as follows.
# emulates blocking read (readpartial). begin result = io.read_nonblock(maxlen) rescue IO::WaitReadable IO.select([io]) retry end
Although IO#read_nonblock
doesn’t raise IO::WaitWritable
. OpenSSL::Buffering#read_nonblock
can raise IO::WaitWritable
. If IO
and SSL should be used polymorphically, IO::WaitWritable
should be rescued too. See the document of OpenSSL::Buffering#read_nonblock
for sample code.
Note that this method is identical to readpartial except the non-blocking flag is set.
By specifying a keyword argument exception to false
, you can indicate that read_nonblock
should not raise an IO::WaitReadable
exception, but return the symbol :wait_readable
instead. At EOF, it will return nil instead of raising EOFError
.
Writes the given string to ios using the write(2) system call after O_NONBLOCK is set for the underlying file descriptor.
It returns the number of bytes written.
write_nonblock
just calls the write(2) system call. It causes all errors the write(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc. The result may also be smaller than string.length (partial write). The caller should care such errors and partial write.
If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN, it is extended by IO::WaitWritable
. So IO::WaitWritable
can be used to rescue the exceptions for retrying write_nonblock.
# Creates a pipe. r, w = IO.pipe # write_nonblock writes only 65536 bytes and return 65536. # (The pipe size is 65536 bytes on this environment.) s = "a" * 100000 p w.write_nonblock(s) #=> 65536 # write_nonblock cannot write a byte and raise EWOULDBLOCK (EAGAIN). p w.write_nonblock("b") # Resource temporarily unavailable (Errno::EAGAIN)
If the write buffer is not empty, it is flushed at first.
When write_nonblock
raises an exception kind of IO::WaitWritable
, write_nonblock
should not be called until io is writable for avoiding busy loop. This can be done as follows.
begin result = io.write_nonblock(string) rescue IO::WaitWritable, Errno::EINTR IO.select(nil, [io]) retry end
Note that this doesn’t guarantee to write all data in string. The length written is reported as result and it should be checked later.
On some platforms such as Windows, write_nonblock
is not supported according to the kind of the IO
object. In such cases, write_nonblock
raises Errno::EBADF
.
By specifying a keyword argument exception to false
, you can indicate that write_nonblock
should not raise an IO::WaitWritable
exception, but return the symbol :wait_writable
instead.
With a block given, passes each element of self
to the block in reverse order:
a = [] (1..4).reverse_each {|element| a.push(element) } # => 1..4 a # => [4, 3, 2, 1] a = [] (1...4).reverse_each {|element| a.push(element) } # => 1...4 a # => [3, 2, 1]
With no block given, returns an enumerator.
Returns object
if it is a regexp:
Regexp.try_convert(/re/) # => /re/
Otherwise if object
responds to :to_regexp
, calls object.to_regexp
and returns the result.
Returns nil
if object
does not respond to :to_regexp
.
Regexp.try_convert('re') # => nil
Raises an exception unless object.to_regexp
returns a regexp.
Clone internal hash.