Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns elements from self; does not modify self.
When a single Integer argument index is given, returns the element at offset index:
a = [:foo, 'bar', 2]
a[0] # => :foo
a[2] # => 2
a # => [:foo, "bar", 2]
If index is negative, counts relative to the end of self:
a = [:foo, 'bar', 2]
a[-1] # => 2
a[-2] # => "bar"
If index is out of range, returns nil.
When two Integer arguments start and length are given, returns a new Array of size length containing successive elements beginning at offset start:
a = [:foo, 'bar', 2]
a[0, 2] # => [:foo, "bar"]
a[1, 2] # => ["bar", 2]
If start + length is greater than self.length, returns all elements from offset start to the end:
a = [:foo, 'bar', 2]
a[0, 4] # => [:foo, "bar", 2]
a[1, 3] # => ["bar", 2]
a[2, 2] # => [2]
If start == self.size and length >= 0, returns a new empty Array.
If length is negative, returns nil.
When a single Range argument range is given, treats range.min as start above and range.size as length above:
a = [:foo, 'bar', 2]
a[0..1] # => [:foo, "bar"]
a[1..2] # => ["bar", 2]
Special case: If range.start == a.size, returns a new empty Array.
If range.end is negative, calculates the end index from the end:
a = [:foo, 'bar', 2]
a[0..-1] # => [:foo, "bar", 2]
a[0..-2] # => [:foo, "bar"]
a[0..-3] # => [:foo]
If range.start is negative, calculates the start index from the end:
a = [:foo, 'bar', 2]
a[-1..2] # => [2]
a[-2..2] # => ["bar", 2]
a[-3..2] # => [:foo, "bar", 2]
If range.start is larger than the array size, returns nil.
a = [:foo, 'bar', 2]
a[4..1] # => nil
a[4..0] # => nil
a[4..-1] # => nil
When a single Enumerator::ArithmeticSequence argument aseq is given, returns an Array of elements corresponding to the indexes produced by the sequence.
a = ['--', 'data1', '--', 'data2', '--', 'data3']
a[(1..).step(2)] # => ["data1", "data2", "data3"]
Unlike slicing with range, if the start or the end of the arithmetic sequence is larger than array size, throws RangeError.
a = ['--', 'data1', '--', 'data2', '--', 'data3']
a[(1..11).step(2)]
# RangeError (((1..11).step(2)) out of range)
a[(7..).step(2)]
# RangeError (((7..).step(2)) out of range)
If given a single argument, and its type is not one of the listed, tries to convert it to Integer, and raises if it is impossible:
a = [:foo, 'bar', 2]
# Raises TypeError (no implicit conversion of Symbol into Integer):
a[:foo]
Array#slice is an alias for Array#[].
 
               VALUE
rb_ary_aref(int argc, const VALUE *argv, VALUE ary)
{
    rb_check_arity(argc, 1, 2);
    if (argc == 2) {
        return rb_ary_aref2(ary, argv[0], argv[1]);
    }
    return rb_ary_aref1(ary, argv[0]);
}
            

Was this page useful?