Results for: "Array"

An Array object is an ordered, integer-indexed collection of objects, called elements; the object represents an array data structure.

An element may be any object (even another array); elements may be any mixture of objects of different types.

Important data structures that use arrays include:

There are also array-like data structures:

Array Indexes

Array indexing starts at 0, as in C or Java.

A non-negative index is an offset from the first element:

A negative index is an offset, backwards, from the end of the array:

In-Range and Out-of-Range Indexes

A non-negative index is in range if and only if it is smaller than the size of the array. For a 3-element array:

A negative index is in range if and only if its absolute value is not larger than the size of the array. For a 3-element array:

Effective Index

Although the effective index into an array is always an integer, some methods (both within class Array and elsewhere) accept one or more non-integer arguments that are integer-convertible objects.

Creating Arrays

You can create an Array object explicitly with:

A number of Ruby methods, both in the core and in the standard library, provide instance method to_a, which converts an object to an array.

Example Usage

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.

Accessing Elements

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]

Obtaining Information about an 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

Adding Items to Arrays

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]

Removing Items from an 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]

Iterating over Arrays

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]

Selecting Items from an 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.

Non-destructive Selection

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]

Destructive Selection

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]

What’s Here

First, what’s elsewhere. Class Array:

Here, class Array provides methods that are useful for:

Methods for Creating an Array

See also Creating Arrays.

Methods for Querying

Methods for Comparing

Methods for Fetching

These methods do not modify self.

Methods for Assigning

These methods add, replace, or reorder elements in self.

Methods for Deleting

Each of these methods removes elements from self:

Methods for Combining

Methods for Iterating

Methods for Converting

Other Methods

No documentation available

Returns an array converted from object.

Tries to convert object to an array using to_ary first and to_a second:

Array([0, 1, 2])        # => [0, 1, 2]
Array({foo: 0, bar: 1}) # => [[:foo, 0], [:bar, 1]]
Array(0..4)             # => [0, 1, 2, 3, 4]

Returns object in an array, [object], if object cannot be converted:

Array(:foo)             # => [:foo]

Returns a new array that is self as a transposed matrix:

a = [[:a0, :a1], [:b0, :b1], [:c0, :c1]]
a.transpose # => [[:a0, :b0, :c0], [:a1, :b1, :c1]]

The elements of self must all be the same size.

Related: see Methods for Converting.

Removes all elements from self; returns self:

a = [:foo, 'bar', 2]
a.clear # => []

Related: see Methods for Deleting.

Returns the first element ele in self such that ele is an array and ele[1] == object:

a = [{foo: 0}, [2, 4], [4, 5, 6], [4, 5]]
a.rassoc(4) # => [2, 4]
a.rassoc(5) # => [4, 5, 6]

Returns nil if no such element is found.

Related: Array#assoc; see also Methods for Fetching.

Returns the element from self found by a binary search, or nil if the search found no suitable element.

See Binary Searching.

Related: see Methods for Fetching.

Returns Ruby object wrapping OLE variant whose variant type is VT_ARRAY. The first argument should be Array object which specifies dimensions and each size of dimensions of OLE array. The second argument specifies variant type of the element of OLE array.

The following create 2 dimensions OLE array. The first dimensions size is 3, and the second is 4.

ole_ary = WIN32OLE::Variant.array([3,4], VT_I4)
ruby_ary = ole_ary.value # => [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Returns a new array, populated with the given objects:

Array[1, 'a', /^A/]    # => [1, "a", /^A/]
Array[]                # => []
Array.[](1, 'a', /^A/) # => [1, "a", /^A/]

Related: see Methods for Creating an Array.

Returns a new array.

With no block and no argument given, returns a new empty array:

Array.new # => []

With no block and array argument given, returns a new array with the same elements:

Array.new([:foo, 'bar', 2]) # => [:foo, "bar", 2]

With no block and integer argument given, returns a new array containing that many instances of the given default_value:

Array.new(0)    # => []
Array.new(3)    # => [nil, nil, nil]
Array.new(2, 3) # => [3, 3]

With a block given, returns an array of the given size; calls the block with each index in the range (0...size); the element at that index in the returned array is the blocks return value:

Array.new(3)  {|index| "Element #{index}" } # => ["Element 0", "Element 1", "Element 2"]

A common pitfall for new Rubyists is providing an expression as default_value:

array = Array.new(2, {})
array # => [{}, {}]
array[0][:a] = 1
array # => [{a: 1}, {a: 1}], as array[0] and array[1] are same object

If you want the elements of the array to be distinct, you should pass a block:

array = Array.new(2) { {} }
array # => [{}, {}]
array[0][:a] = 1
array # => [{a: 1}, {}], as array[0] and array[1] are different objects

Raises TypeError if the first argument is not either an array or an integer-convertible object). Raises ArgumentError if the first argument is a negative integer.

Related: see Methods for Creating an Array.

Returns the new string formed by calling method inspect on each array element:

a = [:foo, 'bar', 2]
a.inspect # => "[:foo, \"bar\", 2]"

Related: see Methods for Converting.

Returns whether both:

Examples:

[:foo, 'bar', 2] == [:foo, 'bar', 2]   # => true
[:foo, 'bar', 2] == [:foo, 'bar', 2.0] # => true
[:foo, 'bar', 2] == [:foo, 'bar']      # => false # Different sizes.
[:foo, 'bar', 2] == [:foo, 'bar', 3]   # => false # Different elements.

This method is different from method Array#eql?, which compares elements using Object#eql?.

Related: see Methods for Comparing.

Returns true if self and other_array are the same size, and if, for each index i in self, self[i].eql?(other_array[i]):

a0 = [:foo, 'bar', 2]
a1 = [:foo, 'bar', 2]
a1.eql?(a0) # => true

Otherwise, returns false.

This method is different from method Array#==, which compares using method Object#==.

Related: see Methods for Querying.

Returns the integer hash value for self.

Two arrays with the same content will have the same hash value (and will compare using eql?):

['a', 'b'].hash == ['a', 'b'].hash # => true
['a', 'b'].hash == ['a', 'c'].hash # => false
['a', 'b'].hash == ['a'].hash      # => false

Returns elements from self; does not modify self.

In brief:

a = [:foo, 'bar', 2]

# Single argument index: returns one element.
a[0]     # => :foo          # Zero-based index.
a[-1]    # => 2             # Negative index counts backwards from end.

# Arguments start and length: returns an array.
a[1, 2]  # => ["bar", 2]
a[-2, 2] # => ["bar", 2]    # Negative start counts backwards from end.

# Single argument range: returns an array.
a[0..1]  # => [:foo, "bar"]
a[0..-2] # => [:foo, "bar"] # Negative range-begin counts backwards from end.
a[-2..2] # => ["bar", 2]    # Negative range-end counts backwards from end.

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 backwards from 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]

Related: see Methods for Fetching.

Assigns elements in self, based on the given object; returns object.

In brief:

a_orig = [:foo, 'bar', 2]

# With argument index.
a = a_orig.dup
a[0] = 'foo' # => "foo"
a # => ["foo", "bar", 2]
a = a_orig.dup
a[7] = 'foo' # => "foo"
a # => [:foo, "bar", 2, nil, nil, nil, nil, "foo"]

# With arguments start and length.
a = a_orig.dup
a[0, 2] = 'foo' # => "foo"
a # => ["foo", 2]
a = a_orig.dup
a[6, 50] = 'foo' # => "foo"
a # => [:foo, "bar", 2, nil, nil, nil, "foo"]

# With argument range.
a = a_orig.dup
a[0..1] = 'foo' # => "foo"
a # => ["foo", 2]
a = a_orig.dup
a[6..50] = 'foo' # => "foo"
a # => [:foo, "bar", 2, nil, nil, nil, "foo"]

When Integer argument index is given, assigns object to an element in self.

If index is non-negative, assigns object the element at offset index:

a = [:foo, 'bar', 2]
a[0] = 'foo' # => "foo"
a # => ["foo", "bar", 2]

If index is greater than self.length, extends the array:

a = [:foo, 'bar', 2]
a[7] = 'foo' # => "foo"
a # => [:foo, "bar", 2, nil, nil, nil, nil, "foo"]

If index is negative, counts backwards from the end of the array:

a = [:foo, 'bar', 2]
a[-1] = 'two' # => "two"
a # => [:foo, "bar", "two"]

When Integer arguments start and length are given and object is not an Array, removes length - 1 elements beginning at offset start, and assigns object at offset start:

a = [:foo, 'bar', 2]
a[0, 2] = 'foo' # => "foo"
a # => ["foo", 2]

If start is negative, counts backwards from the end of the array:

a = [:foo, 'bar', 2]
a[-2, 2] = 'foo' # => "foo"
a # => [:foo, "foo"]

If start is non-negative and outside the array ( >= self.size), extends the array with nil, assigns object at offset start, and ignores length:

a = [:foo, 'bar', 2]
a[6, 50] = 'foo' # => "foo"
a # => [:foo, "bar", 2, nil, nil, nil, "foo"]

If length is zero, shifts elements at and following offset start and assigns object at offset start:

a = [:foo, 'bar', 2]
a[1, 0] = 'foo' # => "foo"
a # => [:foo, "foo", "bar", 2]

If length is too large for the existing array, does not extend the array:

a = [:foo, 'bar', 2]
a[1, 5] = 'foo' # => "foo"
a # => [:foo, "foo"]

When Range argument range is given and object is not an Array, removes length - 1 elements beginning at offset start, and assigns object at offset start:

a = [:foo, 'bar', 2]
a[0..1] = 'foo' # => "foo"
a # => ["foo", 2]

if range.begin is negative, counts backwards from the end of the array:

a = [:foo, 'bar', 2]
a[-2..2] = 'foo' # => "foo"
a # => [:foo, "foo"]

If the array length is less than range.begin, extends the array with nil, assigns object at offset range.begin, and ignores length:

a = [:foo, 'bar', 2]
a[6..50] = 'foo' # => "foo"
a # => [:foo, "bar", 2, nil, nil, nil, "foo"]

If range.end is zero, shifts elements at and following offset start and assigns object at offset start:

a = [:foo, 'bar', 2]
a[1..0] = 'foo' # => "foo"
a # => [:foo, "foo", "bar", 2]

If range.end is negative, assigns object at offset start, retains range.end.abs -1 elements past that, and removes those beyond:

a = [:foo, 'bar', 2]
a[1..-1] = 'foo' # => "foo"
a # => [:foo, "foo"]
a = [:foo, 'bar', 2]
a[1..-2] = 'foo' # => "foo"
a # => [:foo, "foo", 2]
a = [:foo, 'bar', 2]
a[1..-3] = 'foo' # => "foo"
a # => [:foo, "foo", "bar", 2]
a = [:foo, 'bar', 2]

If range.end is too large for the existing array, replaces array elements, but does not extend the array with nil values:

a = [:foo, 'bar', 2]
a[1..5] = 'foo' # => "foo"
a # => [:foo, "foo"]

Related: see Methods for Assigning.

Returns the element of self specified by the given index or nil if there is no such element; index must be an integer-convertible object.

For non-negative index, returns the element of self at offset index:

a = [:foo, 'bar', 2]
a.at(0)   # => :foo
a.at(2)   # => 2
a.at(2.0) # => 2

For negative index, counts backwards from the end of self:

a.at(-2) # => "bar"

Related: Array#[]; see also Methods for Fetching.

Returns the element of self at offset index if index is in range; index must be an integer-convertible object.

With the single argument index and no block, returns the element at offset index:

a = [:foo, 'bar', 2]
a.fetch(1)   # => "bar"
a.fetch(1.1) # => "bar"

If index is negative, counts from the end of the array:

a = [:foo, 'bar', 2]
a.fetch(-1) # => 2
a.fetch(-2) # => "bar"

With arguments index and default_value (which may be any object) and no block, returns default_value if index is out-of-range:

a = [:foo, 'bar', 2]
a.fetch(1, nil)  # => "bar"
a.fetch(3, :foo) # => :foo

With argument index and a block, returns the element at offset index if index is in range (and the block is not called); otherwise calls the block with index and returns its return value:

a = [:foo, 'bar', 2]
a.fetch(1) {|index| raise 'Cannot happen' } # => "bar"
a.fetch(50) {|index| "Value for #{index}" } # => "Value for 50"

Related: see Methods for Fetching.

Adds to self all elements from each array in other_arrays; returns self:

a = [0, 1]
a.concat(['two', 'three'], [:four, :five], a)
# => [0, 1, "two", "three", :four, :five, 0, 1]

Related: see Methods for Assigning.

Returns a new array that is the union of the elements of self and all given arrays other_arrays; items are compared using eql?:

[0, 1, 2, 3].union([4, 5], [6, 7]) # => [0, 1, 2, 3, 4, 5, 6, 7]

Removes duplicates (preserving the first found):

[0, 1, 1].union([2, 1], [3, 1]) # => [0, 1, 2, 3]

Preserves order (preserving the position of the first found):

[3, 2, 1, 0].union([5, 3], [4, 2]) # => [3, 2, 1, 0, 5, 4]

With no arguments given, returns a copy of self.

Related: see Methods for Combining.

Returns a new array containing only those elements from self that are not found in any of the given other_arrays; items are compared using eql?; order from self is preserved:

[0, 1, 1, 2, 1, 1, 3, 1, 1].difference([1]) # => [0, 2, 3]
[0, 1, 2, 3].difference([3, 0], [1, 3])     # => [2]
[0, 1, 2].difference([4])                   # => [0, 1, 2]
[0, 1, 2].difference                        # => [0, 1, 2]

Returns a copy of self if no arguments are given.

Related: Array#-; see also Methods for Combining.

Returns a new array containing each element in self that is eql? to at least one element in each of the given other_arrays; duplicates are omitted:

[0, 0, 1, 1, 2, 3].intersection([0, 1, 2], [0, 1, 3]) # => [0, 1]

Each element must correctly implement method hash.

Order from self is preserved:

[0, 1, 2].intersection([2, 1, 0]) # => [0, 1, 2]

Returns a copy of self if no arguments are given.

Related: see Methods for Combining.

Returns whether other_array has at least one element that is eql? to some element of self:

[1, 2, 3].intersect?([3, 4, 5]) # => true
[1, 2, 3].intersect?([4, 5, 6]) # => false

Each element must correctly implement method hash.

Related: see Methods for Querying.

Appends object as the last element in self; returns self:

[:foo, 'bar', 2] << :baz # => [:foo, "bar", 2, :baz]

Appends object as a single element, even if it is another array:

[:foo, 'bar', 2] << [3, 4] # => [:foo, "bar", 2, [3, 4]]

Related: see Methods for Assigning.

Appends each argument in objects to self; returns self:

a = [:foo, 'bar', 2] # => [:foo, "bar", 2]
a.push(:baz, :bat)   # => [:foo, "bar", 2, :baz, :bat]

Appends each argument as a single element, even if it is another array:

a = [:foo, 'bar', 2]               # => [:foo, "bar", 2]
a.push([:baz, :bat], [:bam, :bad]) # => [:foo, "bar", 2, [:baz, :bat], [:bam, :bad]]

Related: see Methods for Assigning.

Search took: 15ms  ·  Total Results: 2478