This is a result specific to the lex
and lex_file
methods.
This is a result specific to the parse_lex
and parse_lex_file
methods.
A Complex object houses a pair of values, given when the object is created as either rectangular coordinates or polar coordinates.
The rectangular coordinates of a complex number are called the real and imaginary parts; see Complex number definition.
You can create a Complex object from rectangular coordinates with:
A complex literal.
Method
Kernel#Complex
, either with numeric arguments or with certain string arguments.
Method
String#to_c
, for certain strings.
Note that each of the stored parts may be a an instance one of the classes Complex
, Float
, Integer
, or Rational
; they may be retrieved:
Separately, with methods Complex#real
and Complex#imaginary
.
Together, with method Complex#rect
.
The corresponding (computed) polar values may be retrieved:
Separately, with methods Complex#abs
and Complex#arg
.
Together, with method Complex#polar
.
The polar coordinates of a complex number are called the absolute and argument parts; see Complex polar plane.
In this class, the argument part in expressed radians (not degrees).
You can create a Complex object from polar coordinates with:
Method
Kernel#Complex
, with certain string arguments.
Method
String#to_c
, for certain strings.
Note that each of the stored parts may be a an instance one of the classes Complex
, Float
, Integer
, or Rational
; they may be retrieved:
Separately, with methods Complex#abs
and Complex#arg
.
Together, with method Complex#polar
.
The corresponding (computed) rectangular values may be retrieved:
Separately, with methods Complex#real
and Complex#imag
.
Together, with method Complex#rect
.
First, what’s elsewhere:
Class
Complex inherits (directly or indirectly) from classes Numeric and Object.
Includes (indirectly) module Comparable.
Here, class Complex has methods for:
::polar
: Returns a new Complex object based on given polar coordinates.
::rect
(and its alias ::rectangular
): Returns a new Complex object based on given rectangular coordinates.
abs
(and its alias magnitude
): Returns the absolute value for self
.
arg
(and its aliases angle
and phase
): Returns the argument (angle) for self
in radians.
denominator
: Returns the denominator of self
.
finite?
: Returns whether both self.real
and self.image
are finite.
hash
: Returns the integer hash value for self
.
imag
(and its alias imaginary
): Returns the imaginary value for self
.
infinite?
: Returns whether self.real
or self.image
is infinite.
numerator
: Returns the numerator of self
.
polar
: Returns the array [self.abs, self.arg]
.
inspect
: Returns a string representation of self
.
real
: Returns the real value for self
.
real?
: Returns false
; for compatibility with Numeric#real?
.
rect
(and its alias rectangular
): Returns the array [self.real, self.imag]
.
<=>
: Returns whether self
is less than, equal to, or greater than the given argument.
==
: Returns whether self
is equal to the given argument.
rationalize
: Returns a Rational
object whose value is exactly or approximately equivalent to that of self.real
.
to_c
: Returns self
.
to_d: Returns the value as a BigDecimal
object.
to_f
: Returns the value of self.real
as a Float
, if possible.
to_i
: Returns the value of self.real
as an Integer
, if possible.
to_r
: Returns the value of self.real
as a Rational
, if possible.
to_s
: Returns a string representation of self
.
Complex
Arithmetic *
: Returns the product of self
and the given numeric.
**
: Returns self
raised to power of the given numeric.
+
: Returns the sum of self
and the given numeric.
-
: Returns the difference of self
and the given numeric.
-@
: Returns the negation of self
.
/
: Returns the quotient of self
and the given numeric.
abs2
: Returns square of the absolute value (magnitude) for self
.
conj
(and its alias conjugate
): Returns the conjugate of self
.
fdiv
: Returns Complex.rect(self.real/numeric, self.imag/numeric)
.
JSON
::json_create
: Returns a new Complex object, deserialized from the given serialized hash.
as_json
: Returns a serialized hash constructed from self
.
These methods are provided by the JSON gem. To make these methods available:
require 'json/add/complex'
A File object is a representation of a file in the underlying platform.
Class
File extends module FileTest
, supporting such singleton methods as File.exist?
.
Many examples here use these variables:
# English text with newlines. text = <<~EOT First line Second line Fourth line Fifth line EOT # Russian text. russian = "\u{442 435 441 442}" # => "тест" # Binary data. data = "\u9990\u9991\u9992\u9993\u9994" # Text file. File.write('t.txt', text) # File with Russian text. File.write('t.rus', russian) # File with binary data. f = File.new('t.dat', 'wb:UTF-16') f.write(data) f.close
Methods File.new
and File.open
each create a File object for a given file path.
Methods File.new
and File.open
each may take string argument mode
, which:
Begins with a 1- or 2-character read/write mode.
May also contain a 1-character data mode.
May also contain a 1-character file-create mode.
The read/write mode
determines:
Whether the file is to be initially truncated.
Whether reading is allowed, and if so:
The initial read position in the file.
Where in the file reading can occur.
Whether writing is allowed, and if so:
The initial write position in the file.
Where in the file writing can occur.
These tables summarize:
Read/Write Modes for Existing File |------|-----------|----------|----------|----------|-----------| | R/W | Initial | | Initial | | Initial | | Mode | Truncate? | Read | Read Pos | Write | Write Pos | |------|-----------|----------|----------|----------|-----------| | 'r' | No | Anywhere | 0 | Error | - | | 'w' | Yes | Error | - | Anywhere | 0 | | 'a' | No | Error | - | End only | End | | 'r+' | No | Anywhere | 0 | Anywhere | 0 | | 'w+' | Yes | Anywhere | 0 | Anywhere | 0 | | 'a+' | No | Anywhere | End | End only | End | |------|-----------|----------|----------|----------|-----------| Read/Write Modes for \File To Be Created |------|----------|----------|----------|-----------| | R/W | | Initial | | Initial | | Mode | Read | Read Pos | Write | Write Pos | |------|----------|----------|----------|-----------| | 'w' | Error | - | Anywhere | 0 | | 'a' | Error | - | End only | 0 | | 'w+' | Anywhere | 0 | Anywhere | 0 | | 'a+' | Anywhere | 0 | End only | End | |------|----------|----------|----------|-----------|
Note that modes 'r'
and 'r+'
are not allowed for a non-existent file (exception raised).
In the tables:
Anywhere
means that methods IO#rewind
, IO#pos=
, and IO#seek
may be used to change the file’s position, so that allowed reading or writing may occur anywhere in the file.
End only
means that writing can occur only at end-of-file, and that methods IO#rewind
, IO#pos=
, and IO#seek
do not affect writing.
Error
means that an exception is raised if disallowed reading or writing is attempted.
'r'
:
File is not initially truncated:
f = File.new('t.txt') # => #<File:t.txt> f.size == 0 # => false
File’s initial read position is 0:
f.pos # => 0
File may be read anywhere; see IO#rewind
, IO#pos=
, IO#seek
:
f.readline # => "First line\n" f.readline # => "Second line\n" f.rewind f.readline # => "First line\n" f.pos = 1 f.readline # => "irst line\n" f.seek(1, :CUR) f.readline # => "econd line\n"
Writing is not allowed:
f.write('foo') # Raises IOError.
'w'
:
File is initially truncated:
path = 't.tmp' File.write(path, text) f = File.new(path, 'w') f.size == 0 # => true
File’s initial write position is 0:
f.pos # => 0
File may be written anywhere (even past end-of-file); see IO#rewind
, IO#pos=
, IO#seek
:
f.write('foo') f.flush File.read(path) # => "foo" f.pos # => 3 f.write('bar') f.flush File.read(path) # => "foobar" f.pos # => 6 f.rewind f.write('baz') f.flush File.read(path) # => "bazbar" f.pos # => 3 f.pos = 3 f.write('foo') f.flush File.read(path) # => "bazfoo" f.pos # => 6 f.seek(-3, :END) f.write('bam') f.flush File.read(path) # => "bazbam" f.pos # => 6 f.pos = 8 f.write('bah') # Zero padding as needed. f.flush File.read(path) # => "bazbam\u0000\u0000bah" f.pos # => 11
Reading is not allowed:
f.read # Raises IOError.
'a'
:
File is not initially truncated:
path = 't.tmp' File.write(path, 'foo') f = File.new(path, 'a') f.size == 0 # => false
File’s initial position is 0 (but is ignored):
f.pos # => 0
File may be written only at end-of-file; IO#rewind
, IO#pos=
, IO#seek
do not affect writing:
f.write('bar') f.flush File.read(path) # => "foobar" f.write('baz') f.flush File.read(path) # => "foobarbaz" f.rewind f.write('bat') f.flush File.read(path) # => "foobarbazbat"
Reading is not allowed:
f.read # Raises IOError.
'r+'
:
File is not initially truncated:
path = 't.tmp' File.write(path, text) f = File.new(path, 'r+') f.size == 0 # => false
File’s initial read position is 0:
f.pos # => 0
File may be read or written anywhere (even past end-of-file); see IO#rewind
, IO#pos=
, IO#seek
:
f.readline # => "First line\n" f.readline # => "Second line\n" f.rewind f.readline # => "First line\n" f.pos = 1 f.readline # => "irst line\n" f.seek(1, :CUR) f.readline # => "econd line\n" f.rewind f.write('WWW') f.flush File.read(path) # => "WWWst line\nSecond line\nFourth line\nFifth line\n" f.pos = 10 f.write('XXX') f.flush File.read(path) # => "WWWst lineXXXecond line\nFourth line\nFifth line\n" f.seek(-6, :END) # => 0 f.write('YYY') # => 3 f.flush # => #<File:t.tmp> File.read(path) # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n" f.seek(2, :END) f.write('ZZZ') # Zero padding as needed. f.flush File.read(path) # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n\u0000\u0000ZZZ"
'a+'
:
File is not initially truncated:
path = 't.tmp' File.write(path, 'foo') f = File.new(path, 'a+') f.size == 0 # => false
File’s initial read position is 0:
f.pos # => 0
File may be written only at end-of-file; IO#rewind
, IO#pos=
, IO#seek
do not affect writing:
f.write('bar') f.flush File.read(path) # => "foobar" f.write('baz') f.flush File.read(path) # => "foobarbaz" f.rewind f.write('bat') f.flush File.read(path) # => "foobarbazbat"
File may be read anywhere; see IO#rewind
, IO#pos=
, IO#seek
:
f.rewind f.read # => "foobarbazbat" f.pos = 3 f.read # => "barbazbat" f.seek(-3, :END) f.read # => "bat"
Note that modes 'r'
and 'r+'
are not allowed for a non-existent file (exception raised).
'w'
:
File’s initial write position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'w') f.pos # => 0
File may be written anywhere (even past end-of-file); see IO#rewind
, IO#pos=
, IO#seek
:
f.write('foo') f.flush File.read(path) # => "foo" f.pos # => 3 f.write('bar') f.flush File.read(path) # => "foobar" f.pos # => 6 f.rewind f.write('baz') f.flush File.read(path) # => "bazbar" f.pos # => 3 f.pos = 3 f.write('foo') f.flush File.read(path) # => "bazfoo" f.pos # => 6 f.seek(-3, :END) f.write('bam') f.flush File.read(path) # => "bazbam" f.pos # => 6 f.pos = 8 f.write('bah') # Zero padding as needed. f.flush File.read(path) # => "bazbam\u0000\u0000bah" f.pos # => 11
Reading is not allowed:
f.read # Raises IOError.
'a'
:
File’s initial write position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'a') f.pos # => 0
Writing occurs only at end-of-file:
f.write('foo') f.pos # => 3 f.write('bar') f.pos # => 6 f.flush File.read(path) # => "foobar" f.rewind f.write('baz') f.flush File.read(path) # => "foobarbaz"
Reading is not allowed:
f.read # Raises IOError.
'w+'
:
File’s initial position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'w+') f.pos # => 0
File may be written anywhere (even past end-of-file); see IO#rewind
, IO#pos=
, IO#seek
:
f.write('foo') f.flush File.read(path) # => "foo" f.pos # => 3 f.write('bar') f.flush File.read(path) # => "foobar" f.pos # => 6 f.rewind f.write('baz') f.flush File.read(path) # => "bazbar" f.pos # => 3 f.pos = 3 f.write('foo') f.flush File.read(path) # => "bazfoo" f.pos # => 6 f.seek(-3, :END) f.write('bam') f.flush File.read(path) # => "bazbam" f.pos # => 6 f.pos = 8 f.write('bah') # Zero padding as needed. f.flush File.read(path) # => "bazbam\u0000\u0000bah" f.pos # => 11
File may be read anywhere (even past end-of-file); see IO#rewind
, IO#pos=
, IO#seek
:
f.rewind # => 0 f.read # => "bazbam\u0000\u0000bah" f.pos = 3 # => 3 f.read # => "bam\u0000\u0000bah" f.seek(-3, :END) # => 0 f.read # => "bah"
'a+'
:
File’s initial write position is 0:
path = 't.tmp' FileUtils.rm_f(path) f = File.new(path, 'a+') f.pos # => 0
Writing occurs only at end-of-file:
f.write('foo') f.pos # => 3 f.write('bar') f.pos # => 6 f.flush File.read(path) # => "foobar" f.rewind f.write('baz') f.flush File.read(path) # => "foobarbaz"
File may be read anywhere (even past end-of-file); see IO#rewind
, IO#pos=
, IO#seek
:
f.rewind f.read # => "foobarbaz" f.pos = 3 f.read # => "barbaz" f.seek(-3, :END) f.read # => "baz" f.pos = 800 f.read # => ""
To specify whether data is to be treated as text or as binary data, either of the following may be suffixed to any of the string read/write modes above:
't'
: Text data; sets the default external encoding to Encoding::UTF_8
; on Windows, enables conversion between EOL and CRLF and enables interpreting 0x1A
as an end-of-file marker.
'b'
: Binary data; sets the default external encoding to Encoding::ASCII_8BIT
; on Windows, suppresses conversion between EOL and CRLF and disables interpreting 0x1A
as an end-of-file marker.
If neither is given, the stream defaults to text data.
Examples:
File.new('t.txt', 'rt') File.new('t.dat', 'rb')
When the data mode is specified, the read/write mode may not be omitted, and the data mode must precede the file-create mode, if given:
File.new('t.dat', 'b') # Raises an exception. File.new('t.dat', 'rxb') # Raises an exception.
The following may be suffixed to any writable string mode above:
'x'
: Creates the file if it does not exist; raises an exception if the file exists.
Example:
File.new('t.tmp', 'wx')
When the file-create mode is specified, the read/write mode may not be omitted, and the file-create mode must follow the data mode:
File.new('t.dat', 'x') # Raises an exception. File.new('t.dat', 'rxb') # Raises an exception.
When mode is an integer it must be one or more of the following constants, which may be combined by the bitwise OR operator |
:
File::RDONLY
: Open for reading only.
File::WRONLY
: Open for writing only.
File::RDWR
: Open for reading and writing.
File::APPEND
: Open for appending only.
Examples:
File.new('t.txt', File::RDONLY) File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)
Note: Method
IO#set_encoding
does not allow the mode to be specified as an integer.
These constants may also be ORed into the integer mode:
File::CREAT
: Create file if it does not exist.
File::EXCL
: Raise an exception if File::CREAT
is given and the file exists.
Data mode cannot be specified as an integer. When the stream access mode is given as an integer, the data mode is always text, never binary.
Note that although there is a constant File::BINARY
, setting its value in an integer stream mode has no effect; this is because, as documented in File::Constants
, the File::BINARY
value disables line code conversion, but does not change the external encoding.
Any of the string modes above may specify encodings - either external encoding only or both external and internal encodings - by appending one or both encoding names, separated by colons:
f = File.new('t.dat', 'rb') f.external_encoding # => #<Encoding:ASCII-8BIT> f.internal_encoding # => nil f = File.new('t.dat', 'rb:UTF-16') f.external_encoding # => #<Encoding:UTF-16 (dummy)> f.internal_encoding # => nil f = File.new('t.dat', 'rb:UTF-16:UTF-16') f.external_encoding # => #<Encoding:UTF-16 (dummy)> f.internal_encoding # => #<Encoding:UTF-16> f.close
The numerous encoding names are available in array Encoding.name_list
:
Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]
When the external encoding is set, strings read are tagged by that encoding when reading, and strings written are converted to that encoding when writing.
When both external and internal encodings are set, strings read are converted from external to internal encoding, and strings written are converted from internal to external encoding. For further details about transcoding input and output, see Encodings.
If the external encoding is 'BOM|UTF-8'
, 'BOM|UTF-16LE'
or 'BOM|UTF16-BE'
, Ruby
checks for a Unicode BOM in the input document to help determine the encoding. For UTF-16 encodings the file open mode must be binary. If the BOM is found, it is stripped and the external encoding from the BOM is used.
Note that the BOM-style encoding option is case insensitive, so 'bom|utf-8'
is also valid.
A File object has permissions, an octal integer representing the permissions of an actual file in the underlying platform.
Note that file permissions are quite different from the mode of a file stream (File object).
In a File object, the permissions are available thus, where method mode
, despite its name, returns permissions:
f = File.new('t.txt') f.lstat.mode.to_s(8) # => "100644"
On a Unix-based operating system, the three low-order octal digits represent the permissions for owner (6), group (4), and world (4). The triplet of bits in each octal digit represent, respectively, read, write, and execute permissions.
Permissions 0644
thus represent read-write access for owner and read-only access for group and world. See man pages open(2) and chmod(2).
For a directory, the meaning of the execute bit changes: when set, the directory can be searched.
Higher-order bits in permissions may indicate the type of file (plain, directory, pipe, socket, etc.) and various other special features.
On non-Posix operating systems, permissions may include only read-only or read-write, in which case, the remaining permission will resemble typical values. On Windows, for instance, the default permissions are 0644
; The only change that can be made is to make the file read-only, which is reported as 0444
.
For a method that actually creates a file in the underlying platform (as opposed to merely creating a File object), permissions may be specified:
File.new('t.tmp', File::CREAT, 0644) File.new('t.tmp', File::CREAT, 0444)
Permissions may also be changed:
f = File.new('t.tmp', File::CREAT, 0444) f.chmod(0644) f.chmod(0444)
Various constants for use in File and IO
methods may be found in module File::Constants
; an array of their names is returned by File::Constants.constants
.
First, what’s elsewhere. Class
File:
Inherits from class IO, in particular, methods for creating, reading, and writing files
Includes module FileTest
, which provides dozens of additional methods.
Here, class File provides methods that are useful for:
::new
: Opens the file at the given path; returns the file.
::open
: Same as ::new
, but when given a block will yield the file to the block, and close the file upon exiting the block.
::link
: Creates a new name for an existing file using a hard link.
::mkfifo
: Returns the FIFO file created at the given path.
::symlink
: Creates a symbolic link for the given file path.
Paths
::absolute_path
: Returns the absolute file path for the given path.
::absolute_path?
: Returns whether the given path is the absolute file path.
::basename
: Returns the last component of the given file path.
::dirname
: Returns all but the last component of the given file path.
::expand_path
: Returns the absolute file path for the given path, expanding ~
for a home directory.
::extname
: Returns the file extension for the given file path.
::fnmatch?
(aliased as ::fnmatch
): Returns whether the given file path matches the given pattern.
::join
: Joins path components into a single path string.
::path
: Returns the string representation of the given path.
::readlink
: Returns the path to the file at the given symbolic link.
::realdirpath
: Returns the real path for the given file path, where the last component need not exist.
::realpath
: Returns the real path for the given file path, where all components must exist.
::split
: Returns an array of two strings: the directory name and basename of the file at the given path.
path
(aliased as to_path
): Returns the string representation of the given path.
Times
::atime
: Returns a Time
for the most recent access to the given file.
::birthtime
: Returns a Time
for the creation of the given file.
::ctime
: Returns a Time
for the metadata change of the given file.
::mtime
: Returns a Time
for the most recent data modification to the content of the given file.
mtime
: Returns a Time
for the most recent data modification to the content of self
.
Types
::blockdev?
: Returns whether the file at the given path is a block device.
::chardev?
: Returns whether the file at the given path is a character device.
::directory?
: Returns whether the file at the given path is a directory.
::executable?
: Returns whether the file at the given path is executable by the effective user and group of the current process.
::executable_real?
: Returns whether the file at the given path is executable by the real user and group of the current process.
::exist?
: Returns whether the file at the given path exists.
::file?
: Returns whether the file at the given path is a regular file.
::ftype
: Returns a string giving the type of the file at the given path.
::grpowned?
: Returns whether the effective group of the current process owns the file at the given path.
::identical?
: Returns whether the files at two given paths are identical.
::lstat
: Returns the File::Stat
object for the last symbolic link in the given path.
::owned?
: Returns whether the effective user of the current process owns the file at the given path.
::pipe?
: Returns whether the file at the given path is a pipe.
::readable?
: Returns whether the file at the given path is readable by the effective user and group of the current process.
::readable_real?
: Returns whether the file at the given path is readable by the real user and group of the current process.
::setgid?
: Returns whether the setgid bit is set for the file at the given path.
::setuid?
: Returns whether the setuid bit is set for the file at the given path.
::socket?
: Returns whether the file at the given path is a socket.
::stat
: Returns the File::Stat
object for the file at the given path.
::sticky?
: Returns whether the file at the given path has its sticky bit set.
::symlink?
: Returns whether the file at the given path is a symbolic link.
::umask
: Returns the umask value for the current process.
::world_readable?
: Returns whether the file at the given path is readable by others.
::world_writable?
: Returns whether the file at the given path is writable by others.
::writable?
: Returns whether the file at the given path is writable by the effective user and group of the current process.
::writable_real?
: Returns whether the file at the given path is writable by the real user and group of the current process.
lstat
: Returns the File::Stat
object for the last symbolic link in the path for self
.
Contents
::empty?
(aliased as ::zero?
): Returns whether the file at the given path exists and is empty.
::size
: Returns the size (bytes) of the file at the given path.
::size?
: Returns nil
if there is no file at the given path, or if that file is empty; otherwise returns the file size (bytes).
size
: Returns the size (bytes) of self
.
::chmod
: Changes permissions of the file at the given path.
::chown
: Change ownership of the file at the given path.
::lchmod
: Changes permissions of the last symbolic link in the given path.
::lchown
: Change ownership of the last symbolic in the given path.
::lutime
: For each given file path, sets the access time and modification time of the last symbolic link in the path.
::rename
: Moves the file at one given path to another given path.
::utime
: Sets the access time and modification time of each file at the given paths.
flock
: Locks or unlocks self
.
::truncate
: Truncates the file at the given file path to the given size.
::unlink
(aliased as ::delete
): Deletes the file for each given file path.
truncate
: Truncates self
to the given size.
Raised when a method is called on a receiver which doesn’t have it defined and also fails to respond with method_missing
.
"hello".to_ary
raises the exception:
NoMethodError: undefined method `to_ary' for an instance of String
Raised when memory allocation fails.
SystemCallError
is the base class for all low-level platform-dependent errors.
The errors available on the current platform are subclasses of SystemCallError
and are defined in the Errno
module.
File.open("does/not/exist")
raises the exception:
Errno::ENOENT: No such file or directory - does/not/exist
This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator
. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.
Going a step further, the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.
Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator
and customize as needed. (If you find yourself needing this control, have a look at Forwardable
which is also in the standard library. It may suit your needs better.)
SimpleDelegator’s implementation serves as a nice example of the use of Delegator:
require 'delegate' class SimpleDelegator < Delegator def __getobj__ @delegate_sd_obj # return object we are delegating to, required end def __setobj__(obj) @delegate_sd_obj = obj # change delegation object, # a feature we're providing end end
Be advised, RDoc
will not detect delegated methods.
A utility class for managing temporary files.
There are two kind of methods of creating a temporary file:
Tempfile.create
(recommended)
Tempfile.new
and Tempfile.open
(mostly for backward compatibility, not recommended)
Tempfile.create
creates a usual File object. The timing of file deletion is predictable. Also, it supports open-and-unlink technique which removes the temporary file immediately after creation.
Tempfile.new
and Tempfile.open
creates a Tempfile object. The created file is removed by the GC
(finalizer). The timing of file deletion is not predictable.
require 'tempfile' # Tempfile.create with a block # The filename are choosen automatically. # (You can specify the prefix and suffix of the filename by an optional argument.) Tempfile.create {|f| f.puts "foo" f.rewind f.read # => "foo\n" } # The file is removed at block exit. # Tempfile.create without a block # You need to unlink the file in non-block form. f = Tempfile.create f.puts "foo" f.close File.unlink(f.path) # You need to unlink the file. # Tempfile.create(anonymous: true) without a block f = Tempfile.create(anonymous: true) # The file is already removed because anonymous. f.path # => "/tmp/" (no filename since no file) f.puts "foo" f.rewind f.read # => "foo\n" f.close # Tempfile.create(anonymous: true) with a block Tempfile.create(anonymous: true) {|f| # The file is already removed because anonymous. f.path # => "/tmp/" (no filename since no file) f.puts "foo" f.rewind f.read # => "foo\n" } # Not recommended: Tempfile.new without a block file = Tempfile.new('foo') file.path # => A unique filename in the OS's temp directory, # e.g.: "/tmp/foo.24722.0" # This filename contains 'foo' in its basename. file.write("hello world") file.rewind file.read # => "hello world" file.close file.unlink # deletes the temp file
Tempfile.new
and Tempfile.open
This section does not apply to Tempfile.create
because it returns a File
object (not a Tempfile
object).
When you create a Tempfile
object, it will create a temporary file with a unique filename. A Tempfile
objects behaves just like a File
object, and you can perform all the usual file operations on it: reading data, writing data, changing its permissions, etc. So although this class does not explicitly document all instance methods supported by File
, you can in fact call any File
instance method on a Tempfile
object.
A Tempfile
object has a finalizer to remove the temporary file. This means that the temporary file is removed via GC
. This can cause several problems:
Long GC
intervals and conservative GC
can accumulate temporary files that are not removed.
Temporary files are not removed if Ruby
exits abnormally (such as SIGKILL, SEGV).
There are legacy good practices for Tempfile.new
and Tempfile.open
as follows.
When a Tempfile
object is garbage collected, or when the Ruby
interpreter exits, its associated temporary file is automatically deleted. This means that it’s unnecessary to explicitly delete a Tempfile
after use, though it’s a good practice to do so: not explicitly deleting unused Tempfiles can potentially leave behind a large number of temp files on the filesystem until they’re garbage collected. The existence of these temp files can make it harder to determine a new Tempfile
filename.
Therefore, one should always call unlink
or close in an ensure block, like this:
file = Tempfile.new('foo') begin # ...do something with file... ensure file.close file.unlink # deletes the temp file end
Tempfile.create
{ … } exists for this purpose and is more convenient to use. Note that Tempfile.create
returns a File
instance instead of a Tempfile
, which also avoids the overhead and complications of delegation.
Tempfile.create('foo') do |file| # ...do something with file... end
On POSIX systems, it’s possible to unlink a file right after creating it, and before closing it. This removes the filesystem entry without closing the file handle, so it ensures that only the processes that already had the file handle open can access the file’s contents. It’s strongly recommended that you do this if you do not want any other processes to be able to read from or write to the Tempfile
, and you do not need to know the Tempfile’s filename either.
Also, this guarantees the temporary file is removed even if Ruby
exits abnormally. The OS reclaims the storage for the temporary file when the file is closed or the Ruby
process exits (normally or abnormally).
For example, a practical use case for unlink-after-creation would be this: you need a large byte buffer that’s too large to comfortably fit in RAM, e.g. when you’re writing a web server and you want to buffer the client’s file upload data.
‘Tempfile.create(anonymous: true)` supports this behavior. It also works on Windows.
Tempfile’s filename picking method is both thread-safe and inter-process-safe: it guarantees that no other threads or processes will pick the same filename.
Tempfile
itself however may not be entirely thread-safe. If you access the same Tempfile
object from multiple threads then you should protect it with a mutex.
Method
objects are created by Object#method
, and are associated with a particular object (not just with a class). They may be used to invoke the method within the object, and as a block associated with an iterator. They may also be unbound from one object (creating an UnboundMethod
) and bound to another.
class Thing def square(n) n*n end end thing = Thing.new meth = thing.method(:square) meth.call(9) #=> 81 [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9] [ 1, 2, 3 ].each(&method(:puts)) #=> prints 1, 2, 3 require 'date' %w[2017-03-01 2017-03-02].collect(&Date.method(:parse)) #=> [#<Date: 2017-03-01 ((2457814j,0s,0n),+0s,2299161j)>, #<Date: 2017-03-02 ((2457815j,0s,0n),+0s,2299161j)>]
The Comparable
mixin is used by classes whose objects may be ordered. The class must define the <=>
operator, which compares the receiver against another object, returning a value less than 0, returning 0, or returning a value greater than 0, depending on whether the receiver is less than, equal to, or greater than the other object. If the other object is not comparable then the <=>
operator should return nil
. Comparable
uses <=>
to implement the conventional comparison operators (<
, <=
, ==
, >=
, and >
) and the method between?
.
class StringSorter include Comparable attr :str def <=>(other) str.size <=> other.str.size end def initialize(str) @str = str end def inspect @str end end s1 = StringSorter.new("Z") s2 = StringSorter.new("YY") s3 = StringSorter.new("XXX") s4 = StringSorter.new("WWWW") s5 = StringSorter.new("VVVVV") s1 < s2 #=> true s4.between?(s1, s3) #=> false s4.between?(s3, s5) #=> true [ s3, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV]
Module
Comparable provides these methods, all of which use method <=>:
<
: Returns whether self
is less than the given object.
<=
: Returns whether self
is less than or equal to the given object.
==
: Returns whether self
is equal to the given object.
>
: Returns whether self
is greater than the given object.
>=
: Returns whether self
is greater than or equal to the given object.
between?
: Returns true
if self
is between two given objects.
clamp
: For given objects min
and max
, or range (min..max)
, returns:
min
if (self <=> min) < 0
.
max
if (self <=> max) > 0
.
self
otherwise.
Module
Enumerable provides methods that are useful to a collection class for:
These methods return information about the Enumerable other than the elements themselves:
member?
(aliased as include?
): Returns true
if self == object
, false
otherwise.
all?
: Returns true
if all elements meet a specified criterion; false
otherwise.
any?
: Returns true
if any element meets a specified criterion; false
otherwise.
none?
: Returns true
if no element meets a specified criterion; false
otherwise.
one?
: Returns true
if exactly one element meets a specified criterion; false
otherwise.
count
: Returns the count of elements, based on an argument or block criterion, if given.
tally
: Returns a new Hash
containing the counts of occurrences of each element.
These methods return entries from the Enumerable, without modifying it:
Leading, trailing, or all elements:
first
: Returns the first element or leading elements.
take
: Returns a specified number of leading elements.
drop
: Returns a specified number of trailing elements.
take_while
: Returns leading elements as specified by the given block.
drop_while
: Returns trailing elements as specified by the given block.
Minimum and maximum value elements:
min
: Returns the elements whose values are smallest among the elements, as determined by <=> or a given block.
max
: Returns the elements whose values are largest among the elements, as determined by <=> or a given block.
minmax
: Returns a 2-element Array
containing the smallest and largest elements.
min_by
: Returns the smallest element, as determined by the given block.
max_by
: Returns the largest element, as determined by the given block.
minmax_by
: Returns the smallest and largest elements, as determined by the given block.
Groups, slices, and partitions:
group_by
: Returns a Hash
that partitions the elements into groups.
partition
: Returns elements partitioned into two new Arrays, as determined by the given block.
slice_after
: Returns a new Enumerator
whose entries are a partition of self
, based either on a given object
or a given block.
slice_before
: Returns a new Enumerator
whose entries are a partition of self
, based either on a given object
or a given block.
slice_when
: Returns a new Enumerator
whose entries are a partition of self
based on the given block.
chunk
: Returns elements organized into chunks as specified by the given block.
chunk_while
: Returns elements organized into chunks as specified by the given block.
These methods return elements that meet a specified criterion:
find
(aliased as detect
): Returns an element selected by the block.
find_all
(aliased as filter
, select
): Returns elements selected by the block.
find_index
: Returns the index of an element selected by a given object or block.
reject
: Returns elements not rejected by the block.
uniq
: Returns elements that are not duplicates.
These methods return elements in sorted order:
sort
: Returns the elements, sorted by <=> or the given block.
sort_by
: Returns the elements, sorted by the given block.
each_entry
: Calls the block with each successive element (slightly different from each).
each_with_index
: Calls the block with each successive element and its index.
each_with_object
: Calls the block with each successive element and a given object.
each_slice
: Calls the block with successive non-overlapping slices.
each_cons
: Calls the block with successive overlapping slices. (different from each_slice
).
reverse_each
: Calls the block with each successive element, in reverse order.
collect
(aliased as map
): Returns objects returned by the block.
filter_map
: Returns truthy objects returned by the block.
flat_map
(aliased as collect_concat
): Returns flattened objects returned by the block.
grep
: Returns elements selected by a given object or objects returned by a given block.
grep_v
: Returns elements not selected by a given object or objects returned by a given block.
inject
(aliased as reduce
): Returns the object formed by combining all elements.
sum
: Returns the sum of the elements, using method +
.
zip
: Combines each element with elements from other enumerables; returns the n-tuples or calls the block with each.
cycle
: Calls the block with each element, cycling repeatedly.
To use module Enumerable in a collection class:
Include it:
include Enumerable
Implement method each which must yield successive elements of the collection. The method will be called by almost any Enumerable method.
Example:
class Foo include Enumerable def each yield 1 yield 1, 2 yield end end Foo.new.each_entry{ |element| p element }
Output:
1 [1, 2] nil
Ruby
Classes These Ruby
core classes include (or extend) Enumerable:
These Ruby
standard library classes include Enumerable:
CSV
CSV::Table
CSV::Row
Virtually all methods in Enumerable call method each in the including class:
Hash#each
yields the next key-value pair as a 2-element Array
.
Struct#each
yields the next name-value pair as a 2-element Array
.
For the other classes above, each yields the next object from the collection.
The example code snippets for the Enumerable methods:
Always show the use of one or more Array-like classes (often Array
itself).
Sometimes show the use of a Hash-like class. For some methods, though, the usage would not make sense, and so it is not shown. Example: tally
would find exactly one of each Hash
entry.
A Enumerable
class may define extended methods. This section describes the standard behavior of extension methods for reference purposes.
Enumerator has a size method. It uses the size function argument passed to Enumerator.new
.
e = Enumerator.new(-> { 3 }) {|y| p y; y.yield :a; y.yield :b; y.yield :c; :z } p e.size #=> 3 p e.next #=> :a p e.next #=> :b p e.next #=> :c begin e.next rescue StopIteration p $!.result #=> :z end
The result of the size function should represent the number of iterations (i.e., the number of times Enumerator::Yielder#yield is called). In the above example, the block calls yield three times, and the size function, +-> { 3 }+, returns 3 accordingly. The result of the size function can be an integer, Float::INFINITY
, or nil
. An integer means the exact number of times yield will be called, as shown above. Float::INFINITY
indicates an infinite number of yield calls. nil
means the number of yield calls is difficult or impossible to determine.
Many iteration methods return an Enumerator object with an appropriate size function if no block is given.
Examples:
["a", "b", "c"].each.size #=> 3 {a: "x", b: "y", c: "z"}.each.size #=> 3 (0..20).to_a.permutation.size #=> 51090942171709440000 loop.size #=> Float::INFINITY (1..100).drop_while.size #=> nil # size depends on the block's behavior STDIN.each.size #=> nil # cannot be computed without consuming input File.open("/etc/resolv.conf").each.size #=> nil # cannot be computed without reading the file
The behavior of size for Range-based enumerators depends on the begin element:
If the begin element is an Integer
, the size method returns an Integer
or Float::INFINITY
.
If the begin element is an object with a succ method (other than Integer
), size returns nil
. (Computing the size would require repeatedly calling succ, which may be too slow.)
If the begin element does not have a succ method, size raises a TypeError
.
Examples:
(10..42).each.size #=> 33 (10..42.9).each.size #=> 33 (the #end element may be a non-integer numeric) (10..).each.size #=> Float::INFINITY ("a".."z").each.size #=> nil ("a"..).each.size #=> nil (1.0..9.0).each.size # raises TypeError (Float does not have #succ) (..10).each.size # raises TypeError (beginless range has nil as its #begin)
The Enumerable module itself does not define a size method. A class that includes Enumerable may define its own size method. It is recommended that such a size method be consistent with Enumerator#size
.
Array
and Hash
implement size and return values consistent with Enumerator#size
. IO
and Dir
do not define size, which is also consistent because the corresponding enumerator’s size function returns nil
.
However, it is not strictly required for a class’s size method to match Enumerator#size
. For example, File#size
returns the number of bytes in the file, not the number of lines.
FileTest
implements file test operations similar to those used in File::Stat
. It exists as a standalone module, and its methods are also insinuated into the File
class. (Note that this is not done by inclusion: the interpreter cheats).
The Forwardable
module provides delegation of specified methods to a designated object, using the methods def_delegator
and def_delegators
.
For example, say you have a class RecordCollection which contains an array @records
. You could provide the lookup method record_number(), which simply calls [] on the @records
array, like this:
require 'forwardable' class RecordCollection attr_accessor :records extend Forwardable def_delegator :@records, :[], :record_number end
We can use the lookup method like so:
r = RecordCollection.new r.records = [4,5,6] r.record_number(0) # => 4
Further, if you wish to provide the methods size, <<, and map, all of which delegate to @records, this is how you can do it:
class RecordCollection # re-open RecordCollection class def_delegators :@records, :size, :<<, :map end r = RecordCollection.new r.records = [1,2,3] r.record_number(0) # => 1 r.size # => 3 r << 4 # => [1, 2, 3, 4] r.map { |x| x * 2 } # => [2, 4, 6, 8]
You can even extend regular objects with Forwardable
.
my_hash = Hash.new my_hash.extend Forwardable # prepare object for delegation my_hash.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() my_hash.puts "Howdy!"
You could use Forwardable
as an alternative to inheritance, when you don’t want to inherit all methods from the superclass. For instance, here is how you might add a range of Array
instance methods to a new class Queue
:
class Queue extend Forwardable def initialize @q = [ ] # prepare delegate object end # setup preferred interface, enq() and deq()... def_delegator :@q, :push, :enq def_delegator :@q, :shift, :deq # support some general Array methods that fit Queues well def_delegators :@q, :clear, :first, :push, :shift, :size end q = Thread::Queue.new q.enq 1, 2, 3, 4, 5 q.push 6 q.shift # => 1 while q.size > 0 puts q.deq end q.enq "Ruby", "Perl", "Python" puts q.first q.clear puts q.first
This should output:
2 3 4 5 6 Ruby nil
Be advised, RDoc
will not detect delegated methods.
forwardable.rb
provides single-method delegation via the def_delegator
and def_delegators
methods. For full-class delegation via DelegateClass, see delegate.rb
.
mkmf.rb is used by Ruby
C extensions to generate a Makefile which will correctly compile and link the C extension to Ruby
and a third-party library.
Enumerator::ArithmeticSequence
is a subclass of Enumerator
, that is a representation of sequences of numbers with common difference. Instances of this class can be generated by the Range#step
and Numeric#step
methods.
The class can be used for slicing Array
(see Array#slice
) or custom collections.
Subclass of Zlib::Error
When zlib returns a Z_VERSION_ERROR, usually if the zlib library version is incompatible with the version assumed by the caller.
Class Net::HTTP provides a rich library that implements the client in a client-server model that uses the HTTP request-response protocol. For information about HTTP, see:
If you will make only a few GET requests, consider using OpenURI
.
If you will make only a few requests of all kinds, consider using the various singleton convenience methods in this class. Each of the following methods automatically starts and finishes a session that sends a single request:
# Return string response body. Net::HTTP.get(hostname, path) Net::HTTP.get(uri) # Write string response body to $stdout. Net::HTTP.get_print(hostname, path) Net::HTTP.get_print(uri) # Return response as Net::HTTPResponse object. Net::HTTP.get_response(hostname, path) Net::HTTP.get_response(uri) data = '{"title": "foo", "body": "bar", "userId": 1}' Net::HTTP.post(uri, data) params = {title: 'foo', body: 'bar', userId: 1} Net::HTTP.post_form(uri, params) data = '{"title": "foo", "body": "bar", "userId": 1}' Net::HTTP.put(uri, data)
If performance is important, consider using sessions, which lower request overhead. This session has multiple requests for HTTP methods and WebDAV methods:
Net::HTTP.start(hostname) do |http| # Session started automatically before block execution. http.get(path) http.head(path) body = 'Some text' http.post(path, body) # Can also have a block. http.put(path, body) http.delete(path) http.options(path) http.trace(path) http.patch(path, body) # Can also have a block. http.copy(path) http.lock(path, body) http.mkcol(path, body) http.move(path) http.propfind(path, body) http.proppatch(path, body) http.unlock(path, body) # Session finished automatically at block exit. end
The methods cited above are convenience methods that, via their few arguments, allow minimal control over the requests. For greater control, consider using request objects.
On the internet, a URI
(Universal Resource Identifier) is a string that identifies a particular resource. It consists of some or all of: scheme, hostname, path, query, and fragment; see URI syntax.
A Ruby
URI::Generic
object represents an internet URI
. It provides, among others, methods scheme
, hostname
, path
, query
, and fragment
.
An internet URI has a scheme.
The two schemes supported in Net::HTTP are 'https'
and 'http'
:
uri.scheme # => "https" URI('http://example.com').scheme # => "http"
A hostname identifies a server (host) to which requests may be sent:
hostname = uri.hostname # => "jsonplaceholder.typicode.com" Net::HTTP.start(hostname) do |http| # Some HTTP stuff. end
A host-specific path identifies a resource on the host:
_uri = uri.dup _uri.path = '/todos/1' hostname = _uri.hostname path = _uri.path Net::HTTP.get(hostname, path)
A host-specific query adds name/value pairs to the URI:
_uri = uri.dup params = {userId: 1, completed: false} _uri.query = URI.encode_www_form(params) _uri # => #<URI::HTTPS https://jsonplaceholder.typicode.com?userId=1&completed=false> Net::HTTP.get(_uri)
A URI fragment has no effect in Net::HTTP; the same data is returned, regardless of whether a fragment is included.
Request headers may be used to pass additional information to the host, similar to arguments passed in a method call; each header is a name/value pair.
Each of the Net::HTTP methods that sends a request to the host has optional argument headers
, where the headers are expressed as a hash of field-name/value pairs:
headers = {Accept: 'application/json', Connection: 'Keep-Alive'} Net::HTTP.get(uri, headers)
See lists of both standard request fields and common request fields at Request Fields. A host may also accept other custom fields.
A session is a connection between a server (host) and a client that:
Is begun by instance method Net::HTTP#start
.
May contain any number of requests.
Is ended by instance method Net::HTTP#finish
.
See example sessions at Strategies.
If you have many requests to make to a single host (and port), consider using singleton method Net::HTTP.start
with a block; the method handles the session automatically by:
In the block, you can use these instance methods, each of which that sends a single request:
get
, request_get
: GET.
head
, request_head
: HEAD.
post
, request_post
: POST.
delete
: DELETE.
options
: OPTIONS.
trace
: TRACE.
patch
: PATCH.
You can manage a session manually using methods start
and finish
:
http = Net::HTTP.new(hostname) http.start http.get('/todos/1') http.get('/todos/2') http.delete('/posts/1') http.finish # Needed to free resources.
Certain convenience methods automatically handle a session by:
Creating an HTTP object
Starting a session.
Sending a single request.
Finishing the session.
Destroying the object.
Such methods that send GET requests:
::get
: Returns the string response body.
::get_print
: Writes the string response body to $stdout.
::get_response
: Returns a Net::HTTPResponse
object.
Such methods that send POST requests:
::post
: Posts data to the host.
::post_form
: Posts form data to the host.
Many of the methods above are convenience methods, each of which sends a request and returns a string without directly using Net::HTTPRequest and Net::HTTPResponse objects.
You can, however, directly create a request object, send the request, and retrieve the response object; see:
Each returned response is an instance of a subclass of Net::HTTPResponse
. See the response class hierarchy.
In particular, class Net::HTTPRedirection
is the parent of all redirection classes. This allows you to craft a case statement to handle redirections properly:
def fetch(uri, limit = 10) # You should choose a better exception. raise ArgumentError, 'Too many HTTP redirects' if limit == 0 res = Net::HTTP.get_response(URI(uri)) case res when Net::HTTPSuccess # Any success class. res when Net::HTTPRedirection # Any redirection class. location = res['Location'] warn "Redirected to #{location}" fetch(location, limit - 1) else # Any other class. res.value end end fetch(uri)
Basic authentication is performed according to RFC2617:
req = Net::HTTP::Get.new(uri) req.basic_auth('user', 'pass') res = Net::HTTP.start(hostname) do |http| http.request(req) end
By default Net::HTTP reads an entire response into memory. If you are handling large files or wish to implement a progress bar you can instead stream the body directly to an IO
.
Net::HTTP.start(hostname) do |http| req = Net::HTTP::Get.new(uri) http.request(req) do |res| open('t.tmp', 'w') do |f| res.read_body do |chunk| f.write chunk end end end end
HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=
:
Net::HTTP.start(hostname, :use_ssl => true) do |http| req = Net::HTTP::Get.new(uri) res = http.request(req) end
Or if you simply want to make a GET request, you may pass in a URI
object that has an HTTPS URL. Net::HTTP automatically turns on TLS verification if the URI
object has a ‘https’ URI
scheme:
uri # => #<URI::HTTPS https://jsonplaceholder.typicode.com/> Net::HTTP.get(uri)
An HTTP object can have a proxy server.
You can create an HTTP object with a proxy server using method Net::HTTP.new
or method Net::HTTP.start
.
The proxy may be defined either by argument p_addr
or by environment variable 'http_proxy'
.
p_addr
as a String When argument p_addr
is a string hostname, the returned http
has the given host as its proxy:
http = Net::HTTP.new(hostname, nil, 'proxy.example') http.proxy? # => true http.proxy_from_env? # => false http.proxy_address # => "proxy.example" # These use default values. http.proxy_port # => 80 http.proxy_user # => nil http.proxy_pass # => nil
The port, username, and password for the proxy may also be given:
http = Net::HTTP.new(hostname, nil, 'proxy.example', 8000, 'pname', 'ppass') # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false> http.proxy? # => true http.proxy_from_env? # => false http.proxy_address # => "proxy.example" http.proxy_port # => 8000 http.proxy_user # => "pname" http.proxy_pass # => "ppass"
ENV['http_proxy']
’ When environment variable 'http_proxy'
is set to a URI string, the returned http
will have the server at that URI
as its proxy; note that the URI string must have a protocol such as 'http'
or 'https'
:
ENV['http_proxy'] = 'http://example.com' http = Net::HTTP.new(hostname) http.proxy? # => true http.proxy_from_env? # => true http.proxy_address # => "example.com" # These use default values. http.proxy_port # => 80 http.proxy_user # => nil http.proxy_pass # => nil
The URI string may include proxy username, password, and port number:
ENV['http_proxy'] = 'http://pname:ppass@example.com:8000' http = Net::HTTP.new(hostname) http.proxy? # => true http.proxy_from_env? # => true http.proxy_address # => "example.com" http.proxy_port # => 8000 http.proxy_user # => "pname" http.proxy_pass # => "ppass"
With method Net::HTTP.new
(but not Net::HTTP.start
), you can use argument p_no_proxy
to filter proxies:
Reject a certain address:
http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example') http.proxy_address # => nil
Reject certain domains or subdomains:
http = Net::HTTP.new('example.com', nil, 'my.proxy.example', 8000, 'pname', 'ppass', 'proxy.example') http.proxy_address # => nil
Reject certain addresses and port combinations:
http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example:1234') http.proxy_address # => "proxy.example" http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example:8000') http.proxy_address # => nil
Reject a list of the types above delimited using a comma:
http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'my.proxy,proxy.example:8000') http.proxy_address # => nil http = Net::HTTP.new('example.com', nil, 'my.proxy', 8000, 'pname', 'ppass', 'my.proxy,proxy.example:8000') http.proxy_address # => nil
Net::HTTP does not compress the body of a request before sending.
By default, Net::HTTP adds header 'Accept-Encoding'
to a new request object:
Net::HTTP::Get.new(uri)['Accept-Encoding'] # => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
This requests the server to zip-encode the response body if there is one; the server is not required to do so.
Net::HTTP does not automatically decompress a response body if the response has header 'Content-Range'
.
Otherwise decompression (or not) depends on the value of header Content-Encoding:
'deflate'
, 'gzip'
, or 'x-gzip'
: decompresses the body and deletes the header.
'none'
or 'identity'
: does not decompress the body, but deletes the header.
Any other value: leaves the body and header unchanged.
First, what’s elsewhere. Class
Net::HTTP
:
Inherits from class Object.
This is a categorized summary of methods and attributes.
::start: Begins a new session in a new Net::HTTP object.
#started?: Returns whether in a session.
#finish: Ends an active session.
#start: Begins a new session in an existing Net::HTTP object (self
).
:continue_timeout: Returns the continue timeout.
#continue_timeout=: Sets the continue timeout seconds.
:keep_alive_timeout: Returns the keep-alive timeout.
:keep_alive_timeout=: Sets the keep-alive timeout.
:max_retries: Returns the maximum retries.
#max_retries=: Sets the maximum retries.
:open_timeout: Returns the open timeout.
:open_timeout=: Sets the open timeout.
:read_timeout: Returns the open timeout.
:read_timeout=: Sets the read timeout.
:ssl_timeout: Returns the ssl timeout.
:ssl_timeout=: Sets the ssl timeout.
:write_timeout: Returns the write timeout.
write_timeout=: Sets the write timeout.
::get: Sends a GET request and returns the string response body.
::get_print: Sends a GET request and write the string response body to $stdout.
::get_response: Sends a GET request and returns a response object.
::post_form: Sends a POST request with form data and returns a response object.
::post: Sends a POST request with data and returns a response object.
::put: Sends a PUT request with data and returns a response object.
#copy: Sends a COPY request and returns a response object.
#delete: Sends a DELETE request and returns a response object.
#get: Sends a GET request and returns a response object.
#head: Sends a HEAD request and returns a response object.
#lock: Sends a LOCK request and returns a response object.
#mkcol: Sends a MKCOL request and returns a response object.
#move: Sends a MOVE request and returns a response object.
#options: Sends a OPTIONS request and returns a response object.
#patch: Sends a PATCH request and returns a response object.
#post: Sends a POST request and returns a response object.
#propfind: Sends a PROPFIND request and returns a response object.
#proppatch: Sends a PROPPATCH request and returns a response object.
#put: Sends a PUT request and returns a response object.
#request: Sends a request and returns a response object.
#request_get: Sends a GET request and forms a response object; if a block given, calls the block with the object, otherwise returns the object.
#request_head: Sends a HEAD request and forms a response object; if a block given, calls the block with the object, otherwise returns the object.
#request_post: Sends a POST request and forms a response object; if a block given, calls the block with the object, otherwise returns the object.
#send_request: Sends a request and returns a response object.
#trace: Sends a TRACE request and returns a response object.
#unlock: Sends an UNLOCK request and returns a response object.
:close_on_empty_response: Returns whether to close connection on empty response.
:close_on_empty_response=: Sets whether to close connection on empty response.
:ignore_eof: Returns whether to ignore end-of-file when reading a response body with Content-Length
headers.
:ignore_eof=: Sets whether to ignore end-of-file when reading a response body with Content-Length
headers.
:response_body_encoding: Returns the encoding to use for the response body.
#response_body_encoding=: Sets the response body encoding.
:proxy_address: Returns the proxy address.
:proxy_address=: Sets the proxy address.
::proxy_class?: Returns whether self
is a proxy class.
#proxy?: Returns whether self
has a proxy.
#proxy_address: Returns the proxy address.
#proxy_from_env?: Returns whether the proxy is taken from an environment variable.
:proxy_from_env=: Sets whether the proxy is to be taken from an environment variable.
:proxy_pass: Returns the proxy password.
:proxy_pass=: Sets the proxy password.
:proxy_port: Returns the proxy port.
:proxy_port=: Sets the proxy port.
#proxy_user: Returns the proxy user name.
:proxy_user=: Sets the proxy user.
:ca_file: Returns the path to a CA certification file.
:ca_file=: Sets the path to a CA certification file.
:ca_path: Returns the path of to CA directory containing certification files.
:ca_path=: Sets the path of to CA directory containing certification files.
:cert: Returns the OpenSSL::X509::Certificate
object to be used for client certification.
:cert=: Sets the OpenSSL::X509::Certificate
object to be used for client certification.
:cert_store: Returns the X509::Store to be used for verifying peer certificate.
:cert_store=: Sets the X509::Store to be used for verifying peer certificate.
:ciphers: Returns the available SSL ciphers.
:ciphers=: Sets the available SSL ciphers.
:extra_chain_cert: Returns the extra X509 certificates to be added to the certificate chain.
:extra_chain_cert=: Sets the extra X509 certificates to be added to the certificate chain.
:key: Returns the OpenSSL::PKey::RSA
or OpenSSL::PKey::DSA
object.
:key=: Sets the OpenSSL::PKey::RSA
or OpenSSL::PKey::DSA
object.
:max_version: Returns the maximum SSL version.
:max_version=: Sets the maximum SSL version.
:min_version: Returns the minimum SSL version.
:min_version=: Sets the minimum SSL version.
#peer_cert: Returns the X509 certificate chain for the session’s socket peer.
:ssl_version: Returns the SSL version.
:ssl_version=: Sets the SSL version.
#use_ssl=: Sets whether a new session is to use Transport Layer Security.
#use_ssl?: Returns whether self
uses SSL.
:verify_callback: Returns the callback for the server certification verification.
:verify_callback=: Sets the callback for the server certification verification.
:verify_depth: Returns the maximum depth for the certificate chain verification.
:verify_depth=: Sets the maximum depth for the certificate chain verification.
:verify_hostname: Returns the flags for server the certification verification at the beginning of the SSL/TLS session.
:verify_hostname=: Sets he flags for server the certification verification at the beginning of the SSL/TLS session.
:verify_mode: Returns the flags for server the certification verification at the beginning of the SSL/TLS session.
:verify_mode=: Sets the flags for server the certification verification at the beginning of the SSL/TLS session.
:address: Returns the string host name or host IP.
::default_port: Returns integer 80, the default port to use for HTTP
requests.
::http_default_port: Returns integer 80, the default port to use for HTTP
requests.
::https_default_port: Returns integer 443, the default port to use for HTTPS requests.
#ipaddr: Returns the IP address for the connection.
#ipaddr=: Sets the IP address for the connection.
:local_host: Returns the string local host used to establish the connection.
:local_host=: Sets the string local host used to establish the connection.
:local_port: Returns the integer local port used to establish the connection.
:local_port=: Sets the integer local port used to establish the connection.
:port: Returns the integer port number.
::version_1_2? (aliased as ::version_1_2): Returns true; retained for compatibility.
#set_debug_output: Sets the output stream for debugging.
Response class for Continue
responses (status code 100).
A Continue
response indicates that the server has received the request headers.
References:
Response class for Partial Content
responses (status code 206).
The Partial Content
response indicates that the server is delivering only part of the resource (byte serving) due to a Range
header in the request.
References: