Encoding
conversion class.
Mixin module that provides the following:
Access to the CGI
environment variables as methods. See documentation to the CGI
class for a list of these variables. The methods are exposed by removing the leading HTTP_
(if it exists) and downcasing the name. For example, auth_type
will return the environment variable AUTH_TYPE
, and accept
will return the value for HTTP_ACCEPT
.
Access to cookies, including the cookies attribute.
Access to parameters, including the params attribute, and overloading []
to perform parameter value lookup by key.
The initialize_query
method, for initializing the above mechanisms, handling multipart forms, and allowing the class to be used in “offline” mode.
Utility methods for using the RubyGems API.
Helper methods for both Gem::Installer
and Gem::Uninstaller
An Array is an ordered, integer-indexed collection of objects, called elements. Any object may be an Array element.
Array indexing starts at 0, as in C or Java.
A positive index is an offset from the first element:
Index 0 indicates the first element.
Index 1 indicates the second element.
…
A negative index is an offset, backwards, from the end of the array:
Index -1 indicates the last element.
Index -2 indicates the next-to-last element.
…
A non-negative index is in range if it is smaller than the size of the array. For a 3-element array:
Indexes 0 through 2 are in range.
Index 3 is out of range.
A negative index is in range if its absolute value is not larger than the size of the array. For a 3-element array:
Indexes -1 through -3 are in range.
Index -4 is out of range.
You can create an Array object explicitly with:
An array literal.
You can convert certain objects to Arrays with:
Method Array.
An Array can contain different types of objects. For example, the array below contains an Integer
, a String
and a Float:
ary = [1, "two", 3.0] #=> [1, "two", 3.0]
An array can also be created by calling Array.new
with zero, one (the initial size of the Array
) or two arguments (the initial size and a default object).
ary = Array.new #=> [] Array.new(3) #=> [nil, nil, nil] Array.new(3, true) #=> [true, true, true]
Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.
To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:
Array.new(4) {Hash.new} #=> [{}, {}, {}, {}] Array.new(4) {|i| i.to_s } #=> ["0", "1", "2", "3"]
This is also a quick way to build up multi-dimensional arrays:
empty_table = Array.new(3) {Array.new(3)} #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
An array can also be created by using the Array() method, provided by Kernel
, which tries to call to_ary
, then to_a
on its argument.
Array({:a => "a", :b => "b"}) #=> [[:a, "a"], [:b, "b"]]
In addition to the methods it mixes in through the Enumerable
module, the Array
class has proprietary methods for accessing, searching and otherwise manipulating arrays.
Some of the more common ones are illustrated below.
Elements in an array can be retrieved using the Array#[]
method. It can take a single integer argument (a numeric index), a pair of arguments (start and length) or a range. Negative indices start counting from the end, with -1 being the last element.
arr = [1, 2, 3, 4, 5, 6] arr[2] #=> 3 arr[100] #=> nil arr[-3] #=> 4 arr[2, 3] #=> [3, 4, 5] arr[1..4] #=> [2, 3, 4, 5] arr[1..-3] #=> [2, 3, 4]
Another way to access a particular array element is by using the at
method
arr.at(0) #=> 1
The slice
method works in an identical manner to Array#[]
.
To raise an error for indices outside of the array bounds or else to provide a default value when that happens, you can use fetch
.
arr = ['a', 'b', 'c', 'd', 'e', 'f'] arr.fetch(100) #=> IndexError: index 100 outside of array bounds: -6...6 arr.fetch(100, "oops") #=> "oops"
The special methods first
and last
will return the first and last elements of an array, respectively.
arr.first #=> 1 arr.last #=> 6
To return the first n
elements of an array, use take
arr.take(3) #=> [1, 2, 3]
drop
does the opposite of take
, by returning the elements after n
elements have been dropped:
arr.drop(3) #=> [4, 5, 6]
Array
Arrays keep track of their own length at all times. To query an array about the number of elements it contains, use length
, count
or size
.
browsers = ['Chrome', 'Firefox', 'Safari', 'Opera', 'IE'] browsers.length #=> 5 browsers.count #=> 5
To check whether an array contains any elements at all
browsers.empty? #=> false
To check whether a particular item is included in the array
browsers.include?('Konqueror') #=> false
Items can be added to the end of an array by using either push
or <<
arr = [1, 2, 3, 4] arr.push(5) #=> [1, 2, 3, 4, 5] arr << 6 #=> [1, 2, 3, 4, 5, 6]
unshift
will add a new item to the beginning of an array.
arr.unshift(0) #=> [0, 1, 2, 3, 4, 5, 6]
With insert
you can add a new element to an array at any position.
arr.insert(3, 'apple') #=> [0, 1, 2, 'apple', 3, 4, 5, 6]
Using the insert
method, you can also insert multiple values at once:
arr.insert(3, 'orange', 'pear', 'grapefruit') #=> [0, 1, 2, "orange", "pear", "grapefruit", "apple", 3, 4, 5, 6]
Array
The method pop
removes the last element in an array and returns it:
arr = [1, 2, 3, 4, 5, 6] arr.pop #=> 6 arr #=> [1, 2, 3, 4, 5]
To retrieve and at the same time remove the first item, use shift
:
arr.shift #=> 1 arr #=> [2, 3, 4, 5]
To delete an element at a particular index:
arr.delete_at(2) #=> 4 arr #=> [2, 3, 5]
To delete a particular element anywhere in an array, use delete
:
arr = [1, 2, 2, 3] arr.delete(2) #=> 2 arr #=> [1,3]
A useful method if you need to remove nil
values from an array is compact
:
arr = ['foo', 0, nil, 'bar', 7, 'baz', nil] arr.compact #=> ['foo', 0, 'bar', 7, 'baz'] arr #=> ['foo', 0, nil, 'bar', 7, 'baz', nil] arr.compact! #=> ['foo', 0, 'bar', 7, 'baz'] arr #=> ['foo', 0, 'bar', 7, 'baz']
Another common need is to remove duplicate elements from an array.
It has the non-destructive uniq
, and destructive method uniq!
arr = [2, 5, 6, 556, 6, 6, 8, 9, 0, 123, 556] arr.uniq #=> [2, 5, 6, 556, 8, 9, 0, 123]
Like all classes that include the Enumerable
module, Array
has an each method, which defines what elements should be iterated over and how. In case of Array’s each
, all elements in the Array
instance are yielded to the supplied block in sequence.
Note that this operation leaves the array unchanged.
arr = [1, 2, 3, 4, 5] arr.each {|a| print a -= 10, " "} # prints: -9 -8 -7 -6 -5 #=> [1, 2, 3, 4, 5]
Another sometimes useful iterator is reverse_each
which will iterate over the elements in the array in reverse order.
words = %w[first second third fourth fifth sixth] str = "" words.reverse_each {|word| str += "#{word} "} p str #=> "sixth fifth fourth third second first "
The map
method can be used to create a new array based on the original array, but with the values modified by the supplied block:
arr.map {|a| 2*a} #=> [2, 4, 6, 8, 10] arr #=> [1, 2, 3, 4, 5] arr.map! {|a| a**2} #=> [1, 4, 9, 16, 25] arr #=> [1, 4, 9, 16, 25]
Array
Elements can be selected from an array according to criteria defined in a block. The selection can happen in a destructive or a non-destructive manner. While the destructive operations will modify the array they were called on, the non-destructive methods usually return a new array with the selected elements, but leave the original array unchanged.
arr = [1, 2, 3, 4, 5, 6] arr.select {|a| a > 3} #=> [4, 5, 6] arr.reject {|a| a < 3} #=> [3, 4, 5, 6] arr.drop_while {|a| a < 4} #=> [4, 5, 6] arr #=> [1, 2, 3, 4, 5, 6]
select!
and reject!
are the corresponding destructive methods to select
and reject
Similar to select
vs. reject
, delete_if
and keep_if
have the exact opposite result when supplied with the same block:
arr.delete_if {|a| a < 4} #=> [4, 5, 6] arr #=> [4, 5, 6] arr = [1, 2, 3, 4, 5, 6] arr.keep_if {|a| a < 4} #=> [1, 2, 3] arr #=> [1, 2, 3]
First, what’s elsewhere. Class Array:
Inherits from class Object.
Includes module Enumerable, which provides dozens of additional methods.
Here, class Array provides methods that are useful for:
Array
::[]
Returns a new array populated with given objects.
::new
Returns a new array.
::try_convert
Returns a new array created from a given object.
length
, size
Returns the count of elements.
include?
Returns whether any element ==
a given object.
empty?
Returns whether there are no elements.
all?
Returns whether all elements meet a given criterion.
any?
Returns whether any element meets a given criterion.
none?
Returns whether no element ==
a given object.
one?
Returns whether exactly one element ==
a given object.
count
Returns the count of elements that meet a given criterion.
find_index
, index
Returns the index of the first element that meets a given criterion.
rindex
Returns the index of the last element that meets a given criterion.
hash
Returns the integer hash code.
Returns -1, 0, or 1 as self
is less than, equal to, or greater than a given object.
Returns whether each element in self
is ==
to the corresponding element in a given object.
eql?
Returns whether each element in self
is eql?
to the corresponding element in a given object.
These methods do not modify self
.
[]
Returns one or more elements.
fetch
Returns the element at a given offset.
first
Returns one or more leading elements.
last
Returns one or more trailing elements.
max
Returns one or more maximum-valued elements, as determined by <=>
or a given block.
max
Returns one or more minimum-valued elements, as determined by <=>
or a given block.
minmax
Returns the minimum-valued and maximum-valued elements, as determined by <=>
or a given block.
assoc
Returns the first element that is an array whose first element ==
a given object.
rassoc
Returns the first element that is an array whose second element ==
a given object.
at
Returns the element at a given offset.
values_at
Returns the elements at given offsets.
dig
Returns the object in nested objects that is specified by a given index and additional arguments.
drop
Returns trailing elements as determined by a given index.
take
Returns leading elements as determined by a given index.
drop_while
Returns trailing elements as determined by a given block.
take_while
Returns leading elements as determined by a given block.
slice
Returns consecutive elements as determined by a given argument.
sort
Returns all elements in an order determined by <=>
or a given block.
reverse
Returns all elements in reverse order.
compact
Returns an array containing all non-nil
elements.
select
, filter
Returns an array containing elements selected by a given block.
uniq
Returns an array containing non-duplicate elements.
rotate
Returns all elements with some rotated from one end to the other.
bsearch
Returns an element selected via a binary search as determined by a given block.
bsearch_index
Returns the index of an element selected via a binary search as determined by a given block.
sample
Returns one or more random elements.
shuffle
Returns elements in a random order.
These methods add, replace, or reorder elements in self
.
[]=
Assigns specified elements with a given object.
push
, append
, <<
Appends trailing elements.
unshift
, prepend
Prepends leading elements.
insert
Inserts given objects at a given offset; does not replace elements.
concat
Appends all elements from given arrays.
fill
Replaces specified elements with specified objects.
replace
Replaces the content of self
with the content of a given array.
reverse!
Replaces self
with its elements reversed.
rotate!
Replaces self
with its elements rotated.
shuffle!
Replaces self
with its elements in random order.
sort!
Replaces self
with its elements sorted, as determined by <=>
or a given block.
sort_by!
Replaces self
with its elements sorted, as determined by a given block.
Each of these methods removes elements from self
:
pop
Removes and returns the last element.
shift
Removes and returns the first element.
compact!
Removes all non-nil
elements.
delete
Removes elements equal to a given object.
delete_at
Removes the element at a given offset.
delete_if
Removes elements specified by a given block.
keep_if
Removes elements not specified by a given block.
reject!
Removes elements specified by a given block.
select!
, filter!
Removes elements not specified by a given block.
slice!
Removes and returns a sequence of elements.
uniq!
Removes duplicates.
Returns an array containing elements found both in self
and a given array.
intersection
Returns an array containing elements found both in self
and in each given array.
+
Returns an array containing all elements of self
followed by all elements of a given array.
-
Returns an array containiing all elements of self
that are not found in a given array.
Returns an array containing all elements of self
and all elements of a given array, duplicates removed.
union
Returns an array containing all elements of self
and all elements of given arrays, duplicates removed.
difference
Returns an array containing all elements of self
that are not found in any of the given arrays..
product
Returns or yields all combinations of elements from self
and given arrays.
each
Passes each element to a given block.
reverse_each
Passes each element, in reverse order, to a given block.
each_index
Passes each element index to a given block.
cycle
Calls a given block with each element, then does so again, for a specified number of times, or forever.
combination
Calls a given block with combinations of elements of self
; a combination does not use the same element more than once.
permutation
Calls a given block with permutations of elements of self
; a permutation does not use the same element more than once.
repeated_combination
Calls a given block with combinations of elements of self
; a combination may use the same element more than once.
repeated_permutation
Calls a given block with permutations of elements of self
; a permutation may use the same element more than once.
map
, collect
Returns an array containing the block return-value for each element.
map!
, collect!
Replaces each element with a block return-value.
flatten
Returns an array that is a recursive flattening of self
.
flatten!
Replaces each nested array in self
with the elements from that array.
inspect
, to_s
Returns a new String
containing the elements.
join
Returns a newsString containing the elements joined by the field separator.
to_a
Returns self
or a new array containing all elements.
to_ary
Returns self
.
to_h
Returns a new hash formed from the elements.
transpose
Transposes self
, which must be an array of arrays.
zip
Returns a new array of arrays containing self
and given arrays; follow the link for details.
*
Returns one of the following:
With integer argument n
, a new array that is the concatenation of n
copies of self
.
With string argument field_separator
, a new string that is equivalent to join(field_separator)
.
abbrev
Returns a hash of unambiguous abbreviations for elements.
pack
Packs the elements into a binary sequence.
sum
Returns a sum of elements according to either +
or a given block.
for pack.c
An Integer object represents an integer value.
You can create an Integer object explicitly with:
An integer literal.
You can convert certain objects to Integers with:
Method Integer.
An attempt to add a singleton method to an instance of this class causes an exception to be raised.
First, what’s elsewhere. Class Integer:
Inherits from class Numeric.
Here, class Integer provides methods for:
allbits?
Returns whether all bits in self
are set.
anybits?
Returns whether any bits in self
are set.
nobits?
Returns whether no bits in self
are set.
Returns whether self
is less than the given value.
Returns whether self
is less than or equal to the given value.
Returns a number indicating whether self
is less than, equal to, or greater than the given value.
Returns whether self
is greater than the given value.
Returns whether self
is greater than or equal to the given value.
::sqrt
Returns the integer square root of the given value.
::try_convert
Returns the given value converted to an Integer.
Returns the bitwise AND of self
and the given value.
*
Returns the product of self
and the given value.
Returns the value of self
raised to the power of the given value.
+
Returns the sum of self
and the given value.
-
Returns the difference of self
and the given value.
Returns the quotient of self
and the given value.
<<
Returns the value of self
after a leftward bit-shift.
>>
Returns the value of self
after a rightward bit-shift.
[]
Returns a slice of bits from self
.
Returns the bitwise EXCLUSIVE OR of self
and the given value.
ceil
Returns the smallest number greater than or equal to self
.
chr
Returns a 1-character string containing the character represented by the value of self
.
digits
Returns an array of integers representing the base-radix digits of self
.
div
Returns the integer result of dividing self
by the given value.
divmod
Returns a 2-element array containing the quotient and remainder results of dividing self
by the given value.
floor
Returns the greatest number smaller than or equal to self
.
pow
Returns the modular exponentiation of self
.
pred
Returns the integer predecessor of self
.
remainder
Returns the remainder after dividing self
by the given value.
round
Returns self
rounded to the nearest value with the given precision.
truncate
Returns self
truncated to the given precision.
Returns the bitwise OR of self
and the given value.
Numeric
is the class from which all higher-level numeric classes should inherit.
Numeric
allows instantiation of heap-allocated objects. Other core numeric classes such as Integer
are implemented as immediates, which means that each Integer
is a single immutable object which is always passed by value.
a = 1 1.object_id == a.object_id #=> true
There can only ever be one instance of the integer 1
, for example. Ruby ensures this by preventing instantiation. If duplication is attempted, the same instance is returned.
Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class 1.dup #=> 1 1.object_id == 1.dup.object_id #=> true
For this reason, Numeric
should be used when defining other numeric classes.
Classes which inherit from Numeric
must implement coerce
, which returns a two-member Array
containing an object that has been coerced into an instance of the new class and self
(see coerce
).
Inheriting classes should also implement arithmetic operator methods (+
, -
, *
and /
) and the <=>
operator (see Comparable
). These methods may rely on coerce
to ensure interoperability with instances of other numeric classes.
class Tally < Numeric def initialize(string) @string = string end def to_s @string end def to_i @string.size end def coerce(other) [self.class.new('|' * other.to_i), self] end def <=>(other) to_i <=> other.to_i end def +(other) self.class.new('|' * (to_i + other.to_i)) end def -(other) self.class.new('|' * (to_i - other.to_i)) end def *(other) self.class.new('|' * (to_i * other.to_i)) end def /(other) self.class.new('|' * (to_i / other.to_i)) end end tally = Tally.new('||') puts tally * 2 #=> "||||" puts tally > 1 #=> true
First, what’s elsewhere. Class Numeric:
Inherits from class Object.
Includes module Comparable.
Here, class Numeric provides methods for:
finite?
Returns true unless self
is infinite or not a number.
infinite?
Returns -1, nil
or +1, depending on whether self
is -Infinity<tt>, finite, or <tt>+Infinity
.
integer?
Returns whether self
is an integer.
negative?
Returns whether self
is negative.
nonzero?
Returns whether self
is not zero.
positive?
Returns whether self
is positive.
real?
Returns whether self
is a real value.
zero?
Returns whether self
is zero.
Returns:
-1 if self
is less than the given value.
0 if self
is equal to the given value.
1 if self
is greater than the given value.
nil
if self
and the given value are not comparable.
eql?
Returns whether self
and the given value have the same value and type.
-@
Returns the value of self
, negated.
abs2
Returns the square of self
.
ceil
Returns the smallest number greater than or equal to self
, to a given precision.
coerce
Returns array [coerced_self, coerced_other]
for the given other value.
denominator
Returns the denominator (always positive) of the Rational
representation of self
.
div
Returns the value of self
divided by the given value and converted to an integer.
divmod
Returns array [quotient, modulus]
resulting from dividing self
the given divisor.
floor
Returns the largest number less than or equal to self
, to a given precision.
polar
Returns the array [self.abs, self.arg]
.
quo
Returns the value of self
divided by the given value.
real
Returns the real part of self
.
rect
(aliased as rectangular
)
Returns the array [self, 0]
.
remainder
Returns self-arg*(self/arg).truncate
for the given arg
.
round
Returns the value of self
rounded to the nearest value for the given a precision.
truncate
Returns self
truncated (toward zero) to a given precision.
Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM.
As opposed to other stackless light weight concurrency models, each fiber comes with a stack. This enables the fiber to be paused from deeply nested function calls within the fiber block. See the ruby(1) manpage to configure the size of the fiber stack(s).
When a fiber is created it will not run automatically. Rather it must be explicitly asked to run using the Fiber#resume
method. The code running inside the fiber can give up control by calling Fiber.yield
in which case it yields control back to caller (the caller of the Fiber#resume
).
Upon yielding or termination the Fiber
returns the value of the last executed expression
For instance:
fiber = Fiber.new do Fiber.yield 1 2 end puts fiber.resume puts fiber.resume puts fiber.resume
produces
1 2 FiberError: dead fiber called
The Fiber#resume
method accepts an arbitrary number of parameters, if it is the first call to resume
then they will be passed as block arguments. Otherwise they will be the return value of the call to Fiber.yield
Example:
fiber = Fiber.new do |first| second = Fiber.yield first + 2 end puts fiber.resume 10 puts fiber.resume 1_000_000 puts fiber.resume "The fiber will be dead before I can cause trouble"
produces
12 1000000 FiberError: dead fiber called
The concept of non-blocking fiber was introduced in Ruby 3.0. A non-blocking fiber, when reaching a operation that would normally block the fiber (like sleep
, or wait for another process or I/O) will yield control to other fibers and allow the scheduler to handle blocking and waking up (resuming) this fiber when it can proceed.
For a Fiber
to behave as non-blocking, it need to be created in Fiber.new
with blocking: false
(which is the default), and Fiber.scheduler
should be set with Fiber.set_scheduler
. If Fiber.scheduler
is not set in the current thread, blocking and non-blocking fibers’ behavior is identical.
Ruby doesn’t provide a scheduler class: it is expected to be implemented by the user and correspond to Fiber::SchedulerInterface
.
There is also Fiber.schedule
method, which is expected to immediately perform the given block in a non-blocking manner. Its actual implementation is up to the scheduler.
A class which allows both internal and external iteration.
An Enumerator
can be created by the following methods.
Most methods have two forms: a block form where the contents are evaluated for each item in the enumeration, and a non-block form which returns a new Enumerator
wrapping the iteration.
enumerator = %w(one two three).each puts enumerator.class # => Enumerator enumerator.each_with_object("foo") do |item, obj| puts "#{obj}: #{item}" end # foo: one # foo: two # foo: three enum_with_obj = enumerator.each_with_object("foo") puts enum_with_obj.class # => Enumerator enum_with_obj.each do |item, obj| puts "#{obj}: #{item}" end # foo: one # foo: two # foo: three
This allows you to chain Enumerators together. For example, you can map a list’s elements to strings containing the index and the element as a string via:
puts %w[foo bar baz].map.with_index { |w, i| "#{i}:#{w}" } # => ["0:foo", "1:bar", "2:baz"]
An Enumerator
can also be used as an external iterator. For example, Enumerator#next
returns the next value of the iterator or raises StopIteration
if the Enumerator
is at the end.
e = [1,2,3].each # returns an enumerator object. puts e.next # => 1 puts e.next # => 2 puts e.next # => 3 puts e.next # raises StopIteration
Note that enumeration sequence by next
, next_values
, peek
and peek_values
do not affect other non-external enumeration methods, unless the underlying iteration method itself has side-effect, e.g. IO#each_line
.
Moreover, implementation typically uses fibers so performance could be slower and exception stacktraces different than expected.
You can use this to implement an internal iterator as follows:
def ext_each(e) while true begin vs = e.next_values rescue StopIteration return $!.result end y = yield(*vs) e.feed y end end o = Object.new def o.each puts yield puts yield(1) puts yield(1, 2) 3 end # use o.each as an internal iterator directly. puts o.each {|*x| puts x; [:b, *x] } # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3 # convert o.each to an external iterator for # implementing an internal iterator. puts ext_each(o.to_enum) {|*x| puts x; [:b, *x] } # => [], [:b], [1], [:b, 1], [1, 2], [:b, 1, 2], 3
Raised when encountering an object that is not of the expected type.
[1, 2, 3].first("two")
raises the exception:
TypeError: no implicit conversion of String into Integer
Raised when the given index is invalid.
a = [:foo, :bar] a.fetch(0) #=> :foo a[4] #=> nil a.fetch(4) #=> IndexError: index 4 outside of array bounds: -2...2
Raised when the specified key is not found. It is a subclass of IndexError
.
h = {"foo" => :bar} h.fetch("foo") #=> :bar h.fetch("baz") #=> KeyError: key not found: "baz"
Raised when a given numerical value is out of range.
[1, 2, 3].drop(1 << 100)
raises the exception:
RangeError: bignum too big to convert into `long'
Raised when encountering Ruby code with an invalid syntax.
eval("1+1=2")
raises the exception:
SyntaxError: (eval):1: syntax error, unexpected '=', expecting $end
Raised when a file required (a Ruby script, extension library, …) fails to load.
require 'this/file/does/not/exist'
raises the exception:
LoadError: no such file to load -- this/file/does/not/exist
Raised when a given name is invalid or undefined.
puts foo
raises the exception:
NameError: undefined local variable or method `foo' for main:Object
Since constant names must start with a capital:
Integer.const_set :answer, 42
raises the exception:
NameError: wrong constant name answer
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 "hello":String
Raised when there is an attempt to modify a frozen object.
[1, 2, 3].freeze << 4
raises the exception:
FrozenError: can't modify frozen Array
Raised when memory allocation fails.
EncodingError
is the base class for encoding errors.
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
DateTime
A subclass of Date
that easily handles date, hour, minute, second, and offset.
DateTime
class is considered deprecated. Use Time
class.
DateTime
does not consider any leap seconds, does not track any summer time rules.
A DateTime
object is created with DateTime::new
, DateTime::jd
, DateTime::ordinal
, DateTime::commercial
, DateTime::parse
, DateTime::strptime
, DateTime::now
, Time#to_datetime
, etc.
require 'date' DateTime.new(2001,2,3,4,5,6) #=> #<DateTime: 2001-02-03T04:05:06+00:00 ...>
The last element of day, hour, minute, or second can be a fractional number. The fractional number’s precision is assumed at most nanosecond.
DateTime.new(2001,2,3.5) #=> #<DateTime: 2001-02-03T12:00:00+00:00 ...>
An optional argument, the offset, indicates the difference between the local time and UTC. For example, Rational(3,24)
represents ahead of 3 hours of UTC, Rational(-5,24)
represents behind of 5 hours of UTC. The offset should be -1 to +1, and its precision is assumed at most second. The default value is zero (equals to UTC).
DateTime.new(2001,2,3,4,5,6,Rational(3,24)) #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
The offset also accepts string form:
DateTime.new(2001,2,3,4,5,6,'+03:00') #=> #<DateTime: 2001-02-03T04:05:06+03:00 ...>
An optional argument, the day of calendar reform (start
), denotes a Julian day number, which should be 2298874 to 2426355 or negative/positive infinity. The default value is Date::ITALY
(2299161=1582-10-15).
A DateTime
object has various methods. See each reference.
d = DateTime.parse('3rd Feb 2001 04:05:06+03:30') #=> #<DateTime: 2001-02-03T04:05:06+03:30 ...> d.hour #=> 4 d.min #=> 5 d.sec #=> 6 d.offset #=> (7/48) d.zone #=> "+03:30" d += Rational('1.5') #=> #<DateTime: 2001-02-04%16:05:06+03:30 ...> d = d.new_offset('+09:00') #=> #<DateTime: 2001-02-04%21:35:06+09:00 ...> d.strftime('%I:%M:%S %p') #=> "09:35:06 PM" d > DateTime.new(1999) #=> true
DateTime
and when should you use Time
? It’s a common misconception that William Shakespeare and Miguel de Cervantes died on the same day in history - so much so that UNESCO named April 23 as World Book Day because of this fact. However, because England hadn’t yet adopted the Gregorian Calendar Reform (and wouldn’t until 1752) their deaths are actually 10 days apart. Since Ruby’s Time
class implements a proleptic Gregorian calendar and has no concept of calendar reform there’s no way to express this with Time
objects. This is where DateTime
steps in:
shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1616 00:00:00 +0000 cervantes = DateTime.iso8601('1616-04-23', Date::ITALY) #=> Sat, 23 Apr 1616 00:00:00 +0000
Already you can see something is weird - the days of the week are different. Taking this further:
cervantes == shakespeare #=> false (shakespeare - cervantes).to_i #=> 10
This shows that in fact they died 10 days apart (in reality 11 days since Cervantes died a day earlier but was buried on the 23rd). We can see the actual date of Shakespeare’s death by using the gregorian
method to convert it:
shakespeare.gregorian #=> Tue, 03 May 1616 00:00:00 +0000
So there’s an argument that all the celebrations that take place on the 23rd April in Stratford-upon-Avon are actually the wrong date since England is now using the Gregorian calendar. You can see why when we transition across the reform date boundary:
# start off with the anniversary of Shakespeare's birth in 1751 shakespeare = DateTime.iso8601('1751-04-23', Date::ENGLAND) #=> Tue, 23 Apr 1751 00:00:00 +0000 # add 366 days since 1752 is a leap year and April 23 is after February 29 shakespeare + 366 #=> Thu, 23 Apr 1752 00:00:00 +0000 # add another 365 days to take us to the anniversary in 1753 shakespeare + 366 + 365 #=> Fri, 04 May 1753 00:00:00 +0000
As you can see, if we’re accurately tracking the number of solar years since Shakespeare’s birthday then the correct anniversary date would be the 4th May and not the 23rd April.
So when should you use DateTime
in Ruby and when should you use Time
? Almost certainly you’ll want to use Time
since your app is probably dealing with current dates and times. However, if you need to deal with dates and times in a historical context you’ll want to use DateTime
to avoid making the same mistakes as UNESCO. If you also have to deal with timezones then best of luck - just bear in mind that you’ll probably be dealing with local solar times, since it wasn’t until the 19th century that the introduction of the railways necessitated the need for Standard Time and eventually timezones.
Time
is an abstraction of dates and times. Time
is stored internally as the number of seconds with subsecond since the Epoch, 1970-01-01 00:00:00 UTC.
The Time
class treats GMT (Greenwich Mean Time
) and UTC (Coordinated Universal Time
) as equivalent. GMT is the older way of referring to these baseline times but persists in the names of calls on POSIX systems.
Note: A Time object uses the resolution available on your system clock.
All times may have subsecond. Be aware of this fact when comparing times with each other – times that are apparently equal when displayed may be different when compared. (Since Ruby 2.7.0, Time#inspect
shows subsecond but Time#to_s
still doesn’t show subsecond.)
All of these examples were done using the EST timezone which is GMT-5.
You can create a new instance of Time
with Time.new
. This will use the current system time. Time.now
is an alias for this. You can also pass parts of the time to Time.new
such as year, month, minute, etc. When you want to construct a time this way you must pass at least a year. If you pass the year with nothing else time will default to January 1 of that year at 00:00:00 with the current system timezone. Here are some examples:
Time.new(2002) #=> 2002-01-01 00:00:00 -0500 Time.new(2002, 10) #=> 2002-10-01 00:00:00 -0500 Time.new(2002, 10, 31) #=> 2002-10-31 00:00:00 -0500
You can pass a UTC offset:
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
Or a timezone object:
zone = timezone("Europe/Athens") # Eastern European Time, UTC+2 Time.new(2002, 10, 31, 2, 2, 2, zone) #=> 2002-10-31 02:02:02 +0200
You can also use Time.local
and Time.utc
to infer local and UTC timezones instead of using the current system setting.
You can also create a new time using Time.at
which takes the number of seconds (with subsecond) since the Unix Epoch.
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
Once you have an instance of Time
there is a multitude of things you can do with it. Below are some examples. For all of the following examples, we will work on the assumption that you have done the following:
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")
Was that a monday?
t.monday? #=> false
What year was that again?
t.year #=> 1993
Was it daylight savings at the time?
t.dst? #=> false
What’s the day a year later?
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900
How many seconds was that since the Unix Epoch?
t.to_i #=> 730522800
You can also do standard functions like compare two times.
t1 = Time.new(2010) t2 = Time.new(2011) t1 == t2 #=> false t1 == t1 #=> true t1 < t2 #=> true t1 > t2 #=> false Time.new(2010,10,31).between?(t1, t2) #=> true
First, what’s elsewhere. Class Time:
Inherits from class Object.
Includes module Comparable.
Here, class Time provides methods that are useful for:
::new
: Returns a new time from specified arguments (year, month, etc.), including an optional timezone value.
::local
(aliased as ::mktime): Same as ::new
, except the timezone is the local timezone.
::utc
(aliased as ::gm): Same as ::new
, except the timezone is UTC.
::at
: Returns a new time based on seconds since epoch.
::now
: Returns a new time based on the current system time.
+
(plus): Returns a new time increased by the given number of seconds.
- (minus): Returns a new time
decreased by the given number of seconds.
year
: Returns the year of the time.
hour
: Returns the hours value for the time.
min
: Returns the minutes value for the time.
sec
: Returns the seconds value for the time.
usec
(aliased as tv_usec
): Returns the number of microseconds in the subseconds value of the time.
nsec
(aliased as tv_nsec
: Returns the number of nanoseconds in the subsecond part of the time.
subsec
: Returns the subseconds value for the time.
wday
: Returns the integer weekday value of the time (0 == Sunday).
yday
: Returns the integer yearday value of the time (1 == January 1).
hash
: Returns the integer hash value for the time.
utc_offset
(aliased as gmt_offset
and gmtoff
): Returns the offset in seconds between time and UTC.
to_f
: Returns the float number of seconds since epoch for the time.
to_i
(aliased as tv_sec
): Returns the integer number of seconds since epoch for the time.
to_r
: Returns the Rational
number of seconds since epoch for the time.
zone
: Returns a string representation of the timezone of the time.
dst?
(aliased as isdst
): Returns whether the time is DST (daylight saving time).
sunday?
: Returns whether the time is a Sunday.
monday?
: Returns whether the time is a Monday.
tuesday?
: Returns whether the time is a Tuesday.
wednesday?
: Returns whether the time is a Wednesday.
thursday?
: Returns whether the time is a Thursday.
friday?
: Returns whether time is a Friday.
saturday?
: Returns whether the time is a Saturday.
inspect
: Returns the time in detail as a string.
strftime
: Returns the time as a string, according to a given format.
to_a
: Returns a 10-element array of values from the time.
to_s
: Returns a string representation of the time.
getutc
(aliased as getgm
): Returns a new time converted to UTC.
getlocal
: Returns a new time converted to local time.
localtime
: Converts time to local time in place.
round
:Returns a new time with subseconds rounded.
ceil
: Returns a new time with subseconds raised to a ceiling.
floor
: Returns a new time with subseconds lowered to a floor.
A timezone argument must have local_to_utc
and utc_to_local
methods, and may have name
, abbr
, and dst?
methods.
The local_to_utc
method should convert a Time-like object from the timezone to UTC, and utc_to_local
is the opposite. The result also should be a Time
or Time-like object (not necessary to be the same class). The zone
of the result is just ignored. Time-like argument to these methods is similar to a Time
object in UTC without subsecond; it has attribute readers for the parts, e.g. year
, month
, and so on, and epoch time readers, to_i
. The subsecond attributes are fixed as 0, and utc_offset
, zone
, isdst
, and their aliases are same as a Time
object in UTC. Also to_time
, +
, and -
methods are defined.
The name
method is used for marshaling. If this method is not defined on a timezone object, Time
objects using that timezone object can not be dumped by Marshal
.
The abbr
method is used by ‘%Z’ in strftime
.
The dst?
method is called with a Time
value and should return whether the Time
value is in daylight savings time in the zone.
At loading marshaled data, a timezone name will be converted to a timezone object by find_timezone
class method, if the method is defined.
Similarly, that class method will be called when a timezone argument does not have the necessary methods mentioned above.
Expect library adds the IO
instance method expect
, which does similar act to tcl’s expect extension.
In order to use this method, you must require expect:
require 'expect'
Please see expect
for usage.
The IO
class is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream.
Many of the examples in this section use the File
class, the only standard subclass of IO
. The two classes are closely associated. Like the File
class, the Socket
library subclasses from IO
(such as TCPSocket
or UDPSocket
).
The Kernel#open
method can create an IO
(or File
) object for these types of arguments:
A plain string represents a filename suitable for the underlying operating system.
A string starting with "|"
indicates a subprocess. The remainder of the string following the "|"
is invoked as a process with appropriate input/output channels connected to it.
A string equal to "|-"
will create another Ruby instance as a subprocess.
The IO
may be opened with different file modes (read-only, write-only) and encodings for proper conversion. See IO.new
for these options. See Kernel#open
for details of the various command formats described above.
IO.popen
, the Open3
library, or Process#spawn may also be used to communicate with subprocesses through an IO
.
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb"
will be opened as "\gumby\ruby\test.rb"
. When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"C:\\gumby\\ruby\\test.rb"
Our examples here will use the Unix-style forward slashes; File::ALT_SEPARATOR can be used to get the platform-specific separator character.
The global constant ARGF
(also accessible as $<
) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF#path
and its alias ARGF#filename
are provided to access the name of the file currently being read.
The io/console extension provides methods for interacting with the console. The console can be accessed from IO.console
or the standard input/output/error IO
objects.
Requiring io/console adds the following methods:
Example:
require 'io/console' rows, columns = $stdout.winsize puts "Your screen is #{columns} wide and #{rows} tall"
Many examples here use these filenames and their corresponding files:
t.txt
: A text-only file that is assumed to exist via:
text = <<~EOT This is line one. This is the second line. This is the third line. EOT File.write('t.txt', text)
t.dat
: A data file that is assumed to exist via:
data = "\u9990\u9991\u9992\u9993\u9994" f = File.open('t.dat', 'wb:UTF-16') f.write(data) f.close
t.rus
: A Russian-language text file that is assumed to exist via:
File.write('t.rus', "\u{442 435 441 442}")
t.tmp
: A file that is assumed not to exist.
A number of IO method calls must or may specify a mode for the stream; the mode determines how stream is to be accessible, including:
Whether the stream is to be read-only, write-only, or read-write.
Whether the stream is positioned at its beginning or its end.
Whether the stream treats data as text-only or binary.
The external and internal encodings.
When mode
is an integer it must be one or more (combined by bitwise OR (|
) of the modes defined in File::Constants
:
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.
File::CREAT
: Create file if it does not exist.
File::EXCL
: Raise an exception if File::CREAT
is given and the file exists.
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.
When mode
is a string it must begin with one of the following:
'r'
: Read-only stream, positioned at the beginning; the stream cannot be changed to writable.
'w'
: Write-only stream, positioned at the beginning; the stream cannot be changed to readable.
'a'
: Write-only stream, positioned at the end; every write appends to the end; the stream cannot be changed to readable.
'r+'
: Read-write stream, positioned at the beginning.
'w+'
: Read-write stream, positioned at the end.
'a+'
: Read-write stream, positioned at the end.
For a writable file stream (that is, any except read-only), the file is truncated to zero if it exists, and is created if it does not exist.
Examples:
File.open('t.txt', 'r') File.open('t.tmp', 'w')
Either of the following may be suffixed to any of the above:
't'
: Text data; sets the default external encoding to Encoding::UTF_8
; on Windows, enables conversion between EOL and CRLF.
'b'
: Binary data; sets the default external encoding to Encoding::ASCII_8BIT
; on Windows, suppresses conversion between EOL and CRLF.
If neither is given, the stream defaults to text data.
Examples:
File.open('t.txt', 'rt') File.open('t.dat', 'rb')
The following may be suffixed to any writable mode above:
'x'
: Creates the file if it does not exist; raises an exception if the file exists.
Example:
File.open('t.tmp', 'wx')
Finally, the mode string 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>
The numerous encoding names are available in array Encoding.name_list
:
Encoding.name_list.size # => 175 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 Encoding
.
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 number of IO methods accept an optional parameter opts
, which determines how a new stream is to be opened:
:mode
: Stream mode.
:flags
: Integer file open flags; If mode
is also given, the two are bitwise-ORed.
:external_encoding
: External encoding for the stream.
:internal_encoding
: Internal encoding for the stream. '-'
is a synonym for the default internal encoding. If the value is nil
no conversion occurs.
:encoding
: Specifies external and internal encodings as 'extern:intern'
.
:textmode
: If a truthy value, specifies the mode as text-only, binary otherwise.
:binmode
: If a truthy value, specifies the mode as binary, text-only otherwise.
:autoclose
: If a truthy value, specifies that the fd
will close when the stream closes; otherwise it remains open.
Also available are the options offered in String#encode
, which may control conversion between external internal encoding.
A number of IO methods accept optional keyword arguments that determine how a stream is to be treated:
:chomp
: If true
, line separators are omitted; default is false
.
An IO stream has a position, which is the non-negative integer offset (in bytes) in the stream where the next read or write will occur.
Note that a text stream may have multi-byte characters, so a text stream whose position is n
(bytes) may not have n
characters preceding the current position – there may be fewer.
A new stream is initially positioned:
At the beginning (position 0
) if its mode is 'r'
, 'w'
, or 'r+'
.
At the end (position self.size
) if its mode is 'a'
, 'w+'
, or 'a+'
.
Methods to query the position:
IO#tell
and its alias IO#pos
return the position for an open stream.
IO#eof?
and its alias IO#eof
return whether the position is at the end of a readable stream.
Reading from a stream usually changes its position:
f = File.open('t.txt') f.tell # => 0 f.readline # => "This is line one.\n" f.tell # => 19 f.readline # => "This is the second line.\n" f.tell # => 45 f.eof? # => false f.readline # => "Here's the third line.\n" f.eof? # => true
Writing to a stream usually changes its position:
f = File.open('t.tmp', 'w') f.tell # => 0 f.write('foo') # => 3 f.tell # => 3 f.write('bar') # => 3 f.tell # => 6
Iterating over a stream usually changes its position:
f = File.open('t.txt') f.each do |line| p "position=#{f.pos} eof?=#{f.eof?} line=#{line}" end
Output:
"position=19 eof?=false line=This is line one.\n" "position=45 eof?=false line=This is the second line.\n" "position=70 eof?=true line=This is the third line.\n"
The position may also be changed by certain other methods:
IO#pos=
and IO#seek
change the position to a specified offset.
IO#rewind
changes the position to the beginning.
A readable IO stream has a line number, which is the non-negative integer line number in the stream where the next read will occur.
A new stream is initially has line number 0
.
Method IO#lineno
returns the line number.
Reading lines from a stream usually changes its line number:
f = File.open('t.txt', 'r') f.lineno # => 0 f.readline # => "This is line one.\n" f.lineno # => 1 f.readline # => "This is the second line.\n" f.lineno # => 2 f.readline # => "Here's the third line.\n" f.lineno # => 3 f.eof? # => true
Iterating over lines in a stream usually changes its line number:
f = File.open('t.txt') f.each_line do |line| p "position=#{f.pos} eof?=#{f.eof?} line=#{line}" end
Output:
"position=19 eof?=false line=This is line one.\n" "position=45 eof?=false line=This is the second line.\n" "position=70 eof?=true line=This is the third line.\n"
First, what’s elsewhere. Class IO:
Inherits from class Object.
Includes module Enumerable, which provides dozens of additional methods.
Here, class IO provides methods that are useful for:
::open
Creates a new IO object.
::pipe
Creates a connected pair of reader and writer IO objects.
::popen
Creates an IO object to interact with a subprocess.
::select
Selects which given IO instances are ready for reading,
writing, or have pending exceptions.
::binread
Returns a binary string with all or a subset of bytes from the given file.
::read
Returns a string with all or a subset of bytes from the given file.
::readlines
Returns an array of strings, which are the lines from the given file.
getbyte
Returns the next 8-bit byte read from self
as an integer.
getc
Returns the next character read from self
as a string.
gets
Returns the line read from self
.
pread
Returns all or the next n bytes read from self
, not updating the receiver’s offset.
read
Returns all remaining or the next n bytes read from self
for a given n.
read_nonblock
the next n bytes read from self
for a given n, in non-block mode.
readline
Returns the next line read from self
; same as getline, but raises an exception of end-of-file.
readlines
Returns an array of all lines read read from self
.
readpartial
Returns up to the given number of bytes from self
.
::binwrite
Writes the given string to the file at the given filepath, in binary mode.
::write
Writes the given string to self
.
Appends the given string to self
.
print
Prints last read line or given objects to self
.
printf
Writes to self
based on the given format string and objects.
putc
Writes a character to self
.
puts
Writes lines to self
, making sure line ends with a newline.
pwrite
Writes the given string at the given offset, not updating the receiver’s offset.
write
Writes one or more given strings to self
.
write_nonblock
Writes one or more given strings to self
in non-blocking mode.
lineno
Returns the current line number in self
.
lineno=
Sets the line number is self
.
pos=
Sets the byte offset in self
.
reopen
Reassociates self
with a new or existing IO stream.
rewind
Positions self
to the beginning of input.
seek
Sets the offset for self
relative to given position.
::foreach
Yields each line of given file to the block.
each_byte
Calls the given block with each successive byte in self
as an integer.
each_char
Calls the given block with each successive character in self
as a string.
each_codepoint
Calls the given block with each successive codepoint in self
as an integer.
autoclose=
Sets whether self
auto-closes.
binmode
Sets self
to binary mode.
close
Closes self
.
close_on_exec=
Sets the close-on-exec flag.
close_read
Closes self
for reading.
close_write
Closes self
for writing.
set_encoding
Sets the encoding for self
.
set_encoding_by_bom
Sets the encoding for self
, based on its Unicode byte-order-mark.
sync=
Sets the sync-mode to the given value.
autoclose?
Returns whether self
auto-closes.
binmode?
Returns whether self
is in binary mode.
close_on_exec?
Returns the close-on-exec flag for self
.
closed?
Returns whether self
is closed.
external_encoding
Returns the external encoding object for self
.
internal_encoding
Returns the internal encoding object for self
.
stat
Returns the File::Stat
object containing status information for self
.
sync
Returns whether self
is in sync-mode.
isatty
)
Returns whether self
is a terminal.
fdatasync
Immediately writes all buffered data in self
to disk.
flush
Flushes any buffered data within self
to the underlying operating system.
fsync
Immediately writes all buffered data and attributes in self
to disk.
ungetbyte
Prepends buffer for self
with given integer byte or string.
ungetc
Prepends buffer for self
with given string.
::sysopen
Opens the file given by its path, returning the integer file descriptor.
advise
Announces the intention to access data from self
in a specific way.
fcntl
Passes a low-level command to the file specified by the given file descriptor.
ioctl
Passes a low-level command to the device specified by the given file descriptor.
sysread
Returns up to the next n bytes read from self using a low-level read.
sysseek
Sets the offset for self
.
syswrite
Writes the given string to self
using a low-level write.
::copy_stream
Copies data from a source to a destination, each of which is a filepath or an IO-like object.
::try_convert
Returns a new IO object resulting from converting the given object.
inspect
Returns the string representation of self
.