Array

The array class. The elements of an array are arbitrary Ruby objects. See Array Expressions for more information.

Superclass

Included Module

Class Methods

Array[item,...]

Creates an array with arguments as its elements.

Array.new([size[, val]])
Array.new(ary)
Array.new(size) {|index| ... }

Creates an array. When size is specified, an array of that size is created, and it is initialized by nil. If the second argument val is also specified, the object is set to all elements instead of nil. (Note that this does not mean that val is duplicated for each element. References the object val with all the same elements trap::Array).

The second format duplicates and returns the array specified in the argument.

p Array.new([1,2,3]) # => [1,2,3]

The third format sets a value with the evaluation results of the block. The block is executed for each element, so it is possible make all elements a duplicate of a certain object.

p Array.new(5) {|i| i }         # => [0, 1, 2, 3, 4]

ary = Array.new(3, "foo")
ary.each {|obj| p obj.object_id }
# => 537774036
     537774036
     537774036

ary = Array.new(3) { "foo" }
ary.each {|obj| p obj.object_id }
# => 537770448
     537770436
     537770424

Methods

self[nth]

Retrieves the nth item from an array. The index starts from zero. If the nth value is negative, counts backward from the end of the array (the index of the last element is -1). If the nth element does not exist in the array, returns nil.

self[start, length]

Returns an array containing length items from start. If the start value is negative, counts backward from the end of the array (the index of the last element is -1).If length is longer than the length of the array from start, the length of the overlong portion is ignored. Returns nil if length is negative.

self[nth]=val

Changes the nth element of the array into val. If nth is outside the array range, the array will automatically be extended. The extended region will be initialized by nil.

Returns val.

self[start, length]=val

Replaces the length items from index start with the contents of val. If val is not an array, the items will be replaced by the contents of val.to_ary or [val]. Returns val.

ary = [0, 1, 2, 3]
ary[1, 2] = ["a", "b", "c"]
p ary                        # => [0, "a", "b", "c", 3]
ary[2, 1] = 99
p ary                        # => [0, "a", 99, "c", 3]
ary[1, 0] = ["inserted"]
p ary                        # => [0, "inserted", "a", 99, "c", 3]
self + other

Returns a new array with the concatenated contents of self and other. If other is not an array, uses the return value of other.to_ary. If that return value is not an array, throws a TypeError exception.

a = [1, 2]
b = [8, 9]
p a + b     # => [1, 2, 8, 9]
p a         # => [1, 2]        (no change)
p b         # => [8, 9]        (no change here, either)
self * times

Creates and returns a new array that iterated the contents of the array.

p [1, 2, 3] * 3  #=> [1, 2, 3, 1, 2, 3, 1, 2, 3]
self - other

A set subtraction operation. Returns a new array containing self without the elements of other.

self & other

A set intersection operation. Returns a new array containing elements belonging to both arrays. Duplicate elements will be removed.

self | other

A set union operation. Returns a new array containing all elements belonging to either array. Duplicate elements will be removed.

self <=> other

Compares each element with <=> and returns positive integer if self is greater than, 0 if equal to, or a negative integer if less than other. If the end of one array is reached with each element being equal, the shorter array will be treated as being the lesser of the two.

self == other

Compares each element with == and returns TRUE if all elements are equal.

clear

Deletes all elements of an array, making it empty. Returns self.

ary = [1, 2]
ary.clear
p ary     # => []
clone
dup

Returns a new array with the same contents as the receiver. clone returns a complete clone of the original array, including freeze status and singleton methods, while dup duplicates the object contents only. Neither method copies the methods or elements themselves.

compact
compact!

compact returns a new array consisting of self without any nil elements. compact! performs a destructive update; if modified, returns self, if not modified, returns nil.

ary = [1, nil, 2, nil, 3, nil]
p ary.compact   # => [1, 2, 3]
p ary           # => [1, nil, 2, nil, 3, nil]
ary.compact!
p ary           # => [1, 2, 3]
p ary.compact!  # => nil
concat(other)

Appends (destructively) the other array to the end of self. Returns self.

array = [1, 2]
a     = [3, 4]
array.concat a
p array          # => [1, 2, 3, 4]
p a              # => [3, 4]       # this doesn't change
delete(val)
delete(val) { ... }

Deletes all elements equal to val (via ==). When elements equal to val are found, returns val.

If there are no elements equal to val, returns nil. However, if a block has been specified, it will be evaluated and the result returned.

array = [1, 2, 3, 2, 1]
p array.delete(2)       # => 2
p array                 # => [1, 3, 1]

# if the argument is nil and there's no block, there's no way
# to determine from the return value whether it was deleted 
ary = [nil,nil,nil]
p ary.delete(nil)       # => nil
p ary                   # => []
p ary.delete(nil)       # => nil
delete_at(pos)

Removes the element at the position specified by pos and returns the removed element. If pos is out of range, returns nil.

array = [0, 1, 2, 3, 4]
array.delete_at 2
p array             # => [0, 1, 3, 4]
delete_if {|x| ... }
reject! {|x| ... }

Passes elements to the block in order and evaluates them, deleting all those for which the result is true.

delete_if always returns self, while reject! will return self if one or more elements are deleted and nil if none are deleted.

each {|item| .... }

Evaluates a block for each element. Returns self.

# 1, 2, 3 are displayed in order
[1, 2, 3].each do |i|
  puts i
end
each_index {|index| .... }

Evaluates a block for each element's index. Identical to the following:

(0 ... ary.size).each {|index| ....  }

Returns self.

empty?

Returns TRUE if the number of elements in the array is zero.

include?(val)

Returns TRUE if the array contains an element equal to val (using ==).

index(val)

Returns the position of the first element equal to val (using ==). If no such element is found, returns nil.

insert(nth, [val[, val2 ...]])

Inserts the value of the second or later arguments immediately before the nth element. Returns self. Defined as follows:

class Array
  def insert( n, *vals )
    self[n, 0] = vals
    self
  end
end
ary = ["foo", "bar", "baz"]
ary.insert 2, 'a', 'b'
p ary                  # => ["foo", "bar", "a", "b", "baz"]

If no argument val is specified, does nothing.

length
size

Returns the length of the array. If the array is empty, returns zero.

nitems

Returns the number of non-nil elements.

pop

Removes the last element and returns it. If the array is empty, returns nil.

array = [1, [2, 3], 4]
p array.pop      # => 4
p array.pop      # => [2, 3]
p array          # => [1]

p array.pop      # => 1
p array.pop      # => nil
p array          # => []
push(obj1[, obj2 ...])

Appends obj1, obj2 ... to the end of the array, in order.

Returns self.

array = [1, 2, 3]
array.push 4
array.push [5, 6]
array.push 7, 8
p array          # => [1, 2, 3, 4, [5, 6], 7, 8]
reverse
reverse!

reverse returns a new array of all elements in reverse order. reverse! destructively updates the elements in the array.

reverse always returns a new array, while reverse! returns self.

shift

Removes the first element of the array and returns it. The remaining elements are moved up to fill the gap. If the array is empty, returns nil.

sort
sort!
sort {|a, b| ... }
sort! {|a, b| ... }

Sorts the contents of the array. If called with a block, it passes two arguments to the block, then uses the result to compare. Without a block, it compares elements with the operator <=>. sort! destructively updates the elements in the array.

sort returns a new, sorted array, while sort! always returns self.

uniq
uniq!

uniq returns a new array by removing duplicate elements. The remaining elements will then be shifted forward to fill the gaps. uniq! performs destructive deletion and returns self if deletion was performed and nil if it was not.

unshift(obj1[, obj2 ...])

Inserts obj1, obj2 ... to the start of the array, in order.

Returns self.