Programming Ruby

The Pragmatic Programmer's Guide

Contents ^
Next >
class Array
Parent: Object
Version: 1.6

Index:

[ ] new & * + -- << <=> == === [ ] [ ]= | assoc at clear collect collect! compact compact! concat delete delete_at delete_if each each_index empty? eql? fill first flatten flatten! include? index indexes indices join last length map! nitems pack pop push rassoc reject! replace reverse reverse! reverse_each rindex shift size slice slice! sort sort! to_a to_ary to_s uniq uniq! unshift


Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed relative to the end of the array---that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
mixins
Enumerable: collect, detect, each_with_index, entries, find, find_all, grep, include?, map, max, member?, min, reject, select, sort, to_a

class methods
[ ] Array[ [anObject]* ] -> anArray

Returns a new array populated with the given objects. Equivalent to the operator form Array.[]( ... ).

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

new Array.new( anInteger=0, anObject=nil ) -> anArray

Returns a new array, optionally with a size and initial value (that is, anInteger references to the same anObject).

Array.new []
Array.new(2) [nil, nil]
Array.new(5, "A") ["A", "A", "A", "A", "A"]
Array.new(2, Hash.new) [{}, {}]

instance methods
& arr & anOtherArray -> anArray

Set Intersection---Returns a new array containing elements common to the two arrays, with no duplicates.

[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] [1, 3]

* arr * anInteger -> anArray
arr * aString -> anOtherString

Repetition---With a String argument, equivalent to arr.join(aString). Otherwise, returns a new array built by concatenating the anInteger copies of arr.

[ 1, 2, 3 ] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]

+ arr + anOtherArray -> anArray

Concatenation---Returns a new array built by concatenating the two arrays together to produce a third array.

[ 1, 2, 3 ] + [ 4, 5 ] [1, 2, 3, 4, 5]

-- arr - anOtherArray -> anArray

Set Difference---Returns a new array that is a copy of the original array, removing any items that also appear in anOtherArray and duplicated items.

[ 1, 1, 2, 2, 3, 3, 3, 4, 5 ] - [ 1, 2, 4 ] [3, 5]

<< arr << anObject -> arr

Append---Pushes the given object on to the end of this array. This expression returns the array itself, so several appends may be chained together.

See also Array#push .

[ 1, 2 ] << "c" << "d" << [ 3, 4 ] [1, 2, "c", "d", [3, 4]]

<=> arr <=> anOtherArray -> -1, 0, +1

Comparison---Returns an integer -1, 0, or +1 if this array is less than, equal to, or greater than anOtherArray. Each object in each array is compared (using <=>). If any value isn't equal, then that inequality is the return value. If all the values found are equal, then the return is based on a comparison of the array lengths. Thus, two arrays are ``equal'' according to Array#<=> if and only if they have the same length and the value of each element is equal to the value of the corresponding element in the other array.

[ "a", "a", "c" ]    <=> [ "a", "b", "c" ] -1
[ 1, 2, 3, 4, 5, 6 ] <=> [ 1, 2 ] 1

== arr == anOtherArray -> true or false

Equality---Two arrays are equal if they contain the same number of elements and if each element is equal to (according to Object#== ) the corresponding element in the other array.

[ "a", "c" ]    == [ "a", "c", 7 ] false
[ "a", "c", 7 ] == [ "a", "c", 7 ] true
[ "a", "c", 7 ] == [ "a", "d", "f" ] false

=== arr === anOtherArray -> true or false

Case Equality---Equality as evaluated by case expressions. For arrays, this is the same as Array#== .

[ ] arr[anInteger] -> anObject or nil
arr[start, length] -> aSubArray or nil
arr[aRange] -> aSubArray or nil

Element Reference---Returns the element at index anInteger, or returns a subarray starting at index start and continuing for length elements, or returns a subarray specified by aRange. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if any indices are out of range.

a = [ "a", "b", "c", "d", "e" ]
a[2] +  a[0] + a[1] "cab"
a[6] nil
a[1, 2] ["b", "c"]
a[1..3] ["b", "c", "d"]
a[4..7] ["e"]
a[6..10] nil
a[-3, 3] ["c", "d", "e"]

[ ]= arr[anInteger] = anObject -> anObject
arr[start, length] = aSubArray -> aSubArray
arr[aRange] = aSubArray -> aSubArray

Element Assignment---Sets the element at index anInteger, or replaces a subarray starting at index start and continuing for length elements, or replaces a subarray specified by aRange. If anInteger is greater than the current capacity of the array, the array grows automatically. A negative anInteger will count backward from the end of the array. Inserts elements if length is zero. If subArray is nil, deletes elements from arr. An IndexError is raised if a negative index points past the beginning of the array. See also Array#push , Array#unshift .

a = Array.new []
a[4] = "4";                  a [nil, nil, nil, nil, "4"]
a[0, 3] = [ 'a', 'b', 'c' ]; a ["a", "b", "c", nil, "4"]
a[1..2] = [ 1, 2 ];          a ["a", 1, 2, nil, "4"]
a[0, 2] = "?";               a ["?", 2, nil, "4"]
a[0..2] = "A";               a ["A", "4"]
a[-1]   = "Z";               a ["A", "Z"]
a[1..-1] = nil;              a ["A"]

| arr | anOtherArray -> anArray

Set Union---Returns a new array by joining this array with anOtherArray, removing duplicates.

[ "a", "b", "c" ] | [ "c", "d", "a" ] ["a", "b", "c", "d"]

assoc arr.assoc( anObject ) -> anArray or nil

Searches through an array whose elements are also arrays comparing anObject with the first element of each contained array using anObject .== . Returns the first contained array that matches (that is, the first associated array), or nil if no match is found. See also Array#rassoc .

s1 = [ "colors", "red", "blue", "green" ]
s2 = [ "letters", "a", "b", "c" ]
s3 = "foo"
a  = [ s1, s2, s3 ]
a.assoc("letters") ["letters", "a", "b", "c"]
a.assoc("foo") nil

at arr.at( anInteger ) -> anObject or nil

Returns the element at index anInteger. A negative index counts from the end of arr. Returns nil if the index is out of range. See also Array#[] . ( Array#at is slightly faster than Array#[] , as it does not accept ranges and so on.)

a = [ "a", "b", "c", "d", "e" ]
a.at(0) "a"
a.at(-1) "e"

clear arr.clear -> arr

Removes all elements from arr.

a = [ "a", "b", "c", "d", "e" ]
a.clear []

collect arr.collect {| obj | block }

-> anArray

Returns a new array by invoking block once for every element, passing each element as a parameter to block. The result of block is used as the given element in the new array. See also Array#collect! .

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" } ["a!", "b!", "c!", "d!"]
a ["a", "b", "c", "d"]

collect! arr.collect! {| obj | block }

-> arr

Invokes block once for each element of arr, replacing the element with the value returned by block. See also Array#collect .

a = [ "a", "b", "c", "d" ]
a.collect! {|x| x + "!" } ["a!", "b!", "c!", "d!"]
a ["a!", "b!", "c!", "d!"]

compact arr.compact -> anArray

Returns a new array based on the arr with all nil elements removed.

[ "a", nil, "b", nil, "c", nil ].compact ["a", "b", "c"]

compact! arr.compact! -> arr or nil

Same as Array#compact , but modifies the receiver in place. Returns nil if no changes were made.

[ "a", nil, "b", nil, "c" ].compact! ["a", "b", "c"]
[ "a", "b", "c" ].compact! nil

concat arr.concat( anOtherArray ) -> arr

Appends the elements in anOtherArray to arr.

[ "a", "b" ].concat( ["c", "d"] ) ["a", "b", "c", "d"]

delete arr.delete( anObject ) -> anObject or nil
arr.delete( anObject ) {| | block }

-> anObject or nil

Deletes items from the self that are equal to anObject. If the item is not found, returns nil. If the optional code block is given, returns the result of block if the item is not found.

a = [ "a", "b", "b", "b", "c" ]
a.delete("b") "b"
a ["a", "c"]
a.delete("z") nil
a.delete("z") { "not found" } "not found"

delete_at arr.delete_at( anIndex ) -> anObject or nil

Deletes the element at the specified index, returning that element, or nil if the index is out of range. See also Array#slice! .

a = %w( ant bat cat dog )
a.delete_at(2) "cat"
a ["ant", "bat", "dog"]
a.delete_at(99) nil

delete_if arr.delete_if {| | block }

-> arr

Deletes every element of arr for which block evaluates to true.

a = [ "a", "b", "c" ]
a.delete_if {|x| x >= "b" } ["a"]

each arr.each {| item | block } -> arr

Calls block once for each element in arr, passing that element as a parameter.

a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
produces:
a -- b -- c --

each_index arr.each_index {| anIndex | block } -> arr

Same as Array#each , but passes the index of the element instead of the element itself.

a = [ "a", "b", "c" ]
a.each_index {|x| print x, " -- " }
produces:
0 -- 1 -- 2 --

empty? arr.empty? -> true or false

Returns true if arr array contains no elements.

[].empty? true

eql? arr.eql?( anOtherArray ) -> true or false

An array is equal to another array if the lengths are equal and each corresponding element is equal (according to Object#eql? ). See also Array#<=> . eql? is used for Hash comparison.

[ "a", "b", "c" ].eql?(["a", "b", "c"]) true
[ "a", "b", "c" ].eql?(["a", "b"]) false
[ "a", "b", "c" ].eql?(["b", "c", "d"]) false

fill arr.fill( anObject ) -> arr
arr.fill( anObject, start [, length ] ) -> arr
arr.fill( anObject, aRange ) -> arr

Sets the selected elements of arr (which may be the entire array) to anObject. A start of nil is equivalent to zero. A length of nil is equivalent to arr.length.

a = [ "a", "b", "c", "d" ]
a.fill("x") ["x", "x", "x", "x"]
a.fill("z", 2, 2) ["x", "x", "z", "z"]
a.fill("y", 0..1) ["y", "y", "z", "z"]

first arr.first -> anObject or nil

Returns the first element of the array. If the array is empty, returns nil.

a = [ "q", "r", "s", "t" ]
a.first "q"

flatten arr.flatten -> anArray

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array.

s = [ 1, 2, 3 ] [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

flatten! arr.flatten! -> arr or nil

Same as Array#flatten , but modifies the receiver in place. Returns nil if no modifications were made (i.e., arr contains no subarrays.)

a = [ 1, 2, [3, [4, 5] ] ]
a.flatten! [1, 2, 3, 4, 5]
a.flatten! nil
a [1, 2, 3, 4, 5]

include? arr.include?( anObject ) -> true or false

Returns true if the given object is present in arr (that is, if any object == anObject), false otherwise.

a = [ "a", "b", "c" ]
a.include?("b") true
a.include?("z") false

Template characters for Array#pack
Directive Meaning
@ Moves to absolute position
A ASCII string (space padded, count is width)
a ASCII string (null padded, count is width)
B Bit string (descending bit order)
b Bit string (ascending bit order)
C Unsigned char
c Char
d Double-precision float, native format
E Double-precision float, little-endian byte order
e Single-precision float, little-endian byte order
f Single-precision float, native format
G Double-precision float, network (big-endian) byte order
g Single-precision float, network (big-endian) byte order
H Hex string (high nibble first)
h Hex string (low nibble first)
I Unsigned integer
i Integer
L Unsigned long
l Long
M Quoted printable, MIME encoding (see RFC2045)
m Base64 encoded string
N Long, network (big-endian) byte order
n Short, network (big-endian) byte-order
P Pointer to a structure (fixed-length string)
p Pointer to a null-terminated string
S Unsigned short
s Short
U UTF-8
u UU-encoded string
V Long, little-endian byte order
v Short, little-endian byte order
X Back up a byte
x Null byte
Z Same as ``A''

index arr.index( anObject ) -> anInteger or nil

Returns the index of the first object in arr such that the object == anObject. Returns nil if no match is found.

a = [ "a", "b", "c" ]
a.index("b") 1
a.index("z") nil

indexes arr.indexes( i1, i2, ... iN ) -> anArray

Returns a new array consisting of elements at the given indices. May insert nil for indices out of range.

a = [ "a", "b", "c", "d", "e", "f", "g" ]
a.indexes(0, 2, 4) ["a", "c", "e"]
a.indexes(0, 2, 4, 12) ["a", "c", "e", nil]

indices arr.indices( i1, i2, ... iN ) -> anArray

Synonym for Array#indexes .

join arr.join( aSepString=$, ) -> aString

Returns a string created by converting each element of the array to a string, separated by aSepString.

[ "a", "b", "c" ].join "abc"
[ "a", "b", "c" ].join("-") "a-b-c"

last arr.last -> anObject or nil

Returns the last element of arr. If the array is empty, returns nil.

[ "w", "x", "y", "z" ].last "z"

length arr.length -> anInteger

Returns the number of elements in arr. May be zero.

[ 1, 2, 3, 4, 5 ].length 5

map! arr.map! {| obj | block }

-> arr

Synonym for Array#collect! .

nitems arr.nitems -> anInteger

Returns the number of non-nil elements in arr. May be zero.

[ 1, nil, 3, nil, 5 ].nitems 3

pack arr.pack ( aTemplateString ) -> aBinaryString
Packs the contents of arr into a binary sequence according to the directives in aTemplateString (see Table 22.1 on page 285). Directives ``A,'' ``a,'' and ``Z'' may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (``*''), all remaining array elements will be converted. Any of the directives ``sSiIlL'' may be followed by an underscore (``_'') to use the underlying platform's native size for the specified type; otherwise, they use a platform-independent size. Spaces are ignored in the template string. See also String#unpack on page 378.

a = [ "a", "b", "c" ]
n = [ 65, 66, 67 ]
a.pack("A3A3A3") "a[visible space][visible space]b[visible space][visible space]c[visible space][visible space]"
a.pack("a3a3a3") "a\000\000b\000\000c\000\000"
n.pack("ccc") "ABC"

pop arr.pop -> anObject or nil

Removes the last element from arr and returns it, or nil if the array is empty (as with a stack).

a = [ "a", "m", "z" ]
a.pop "z"
a ["a", "m"]

push arr.push( [ anObject ]+ ) -> arr

Appends the given argument(s) to the end of arr (as with a stack).

a = [ "a", "b", "c" ]
a.push("d", "e", "f") ["a", "b", "c", "d", "e", "f"]

rassoc arr.rassoc( key ) -> anArray or nil

Searches through the array whose elements are also arrays. Compares key with the second element of each contained array using ==. Returns the first contained array that matches. See also assoc.

a = [ [ 1, "one"], [2, "two"], [3, "three"], ["ii", "two"] ]
a.rassoc("two") [2, "two"]
a.rassoc("four") nil

reject! arr.reject! {| | block }

-> arr or nil

Equivalent to Array#delete_if , but returns nil if no changes were made.

replace arr.replace( anOtherArray ) -> arr

Replaces the contents of arr with the contents of anOtherArray, truncating or expanding if necessary.

a = [ "a", "b", "c", "d", "e" ]
a.replace( [ "x", "y", "z" ] ) ["x", "y", "z"]
a ["x", "y", "z"]

reverse arr.reverse -> anArray

Returns a new array using arr's elements in reverse order.

[ "a", "b", "c" ].reverse ["c", "b", "a"]
[ 1 ].reverse [1]

reverse! arr.reverse! -> arr or nil

Same as reverse, but returns nil if arr is unchanged (arr .length is zero or one).

a = [ "a", "b", "c" ]
a.reverse! ["c", "b", "a"]
a ["c", "b", "a"]
[ 1 ].reverse! nil

reverse_each arr.reverse_each {| | block }

Same as Array#each , but traverses arr in reverse order.

a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }
produces:
c b a

rindex arr.rindex( anObject ) -> anInteger or nil

Returns the index of the last object in arr such that the object == anObject. Returns nil if no match is found.

a = [ "a", "b", "b", "b", "c" ]
a.rindex("b") 3
a.rindex("z") nil

shift arr.shift -> anObject or nil

Returns the first element of arr and removes it (shifting all other elements down by one). Returns nil if the array is empty.

args = [ "-m", "-q", "filename" ]
args.shift "-m"
args ["-q", "filename"]

size arr.size -> anInteger

Synonym for Array#length .

slice arr.slice( anInteger ) -> anObject
arr.slice( start, length ) -> aSubArray
arr.slice( aRange ) -> aSubArray

Synonym for Array#[ ] .

a = [ "a", "b", "c", "d", "e" ]
a.slice(2) + a.slice(0) + a.slice(1) "cab"
a.slice(6) nil
a.slice(1, 2) ["b", "c"]
a.slice(1..3) ["b", "c", "d"]
a.slice(4..7) ["e"]
a.slice(6..10) nil
a.slice(-3, 3) ["c", "d", "e"]

slice! arr.slice!( anInteger ) -> anObject or nil
arr.slice!( start, length ) -> aSubArray or nil
arr.slice!( aRange ) -> aSubArray or nil

Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if the index is out of range. Equivalent to:

def slice!(*args)
  result = self[*args]
  self[*args] = nil
  result
end

a = [ "a", "b", "c" ]
a.slice!(1) "b"
a ["a", "c"]
a.slice!(-1) "c"
a ["a"]
a.slice!(100) nil
a ["a"]

sort arr.sort -> anArray
arr.sort {| a,b | block }

-> anArray

Returns a new array created by sorting arr. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1.

a = [ "d", "a", "e", "c", "b" ]
a.sort ["a", "b", "c", "d", "e"]
a.sort {|x,y| y <=> x } ["e", "d", "c", "b", "a"]

sort! arr.sort! -> arr
arr.sort! {| a,b | block }

-> arr

Same as Array#sort , but modifies the receiver in place. arr is effectively frozen while a sort is in progress.

a = [ "d", "a", "e", "c", "b" ]
a.sort! ["a", "b", "c", "d", "e"]
a ["a", "b", "c", "d", "e"]

to_a arr.to_a -> arr

Returns arr.

to_ary arr.to_ary -> arr

Synonym for Array#to_a .

to_s arr.to_s -> aString

Returns arr .join.

[ "a", "e", "i", "o" ].to_s "aeio"

uniq arr.uniq -> anArray

Returns a new array by removing duplicate values in arr.

a = [ "a", "a", "b", "b", "c" ]
a.uniq ["a", "b", "c"]

uniq! arr.uniq! -> arr or nil

Same as Array#uniq , but modifies the receiver in place. Returns nil if no changes are made (that is, no duplicates are found).

a = [ "a", "a", "b", "b", "c" ]
a.uniq! ["a", "b", "c"]
b = [ "a", "b", "c" ]
b.uniq! nil

unshift arr.unshift( anObject ) -> arr

Prepends anObject to the front of arr, and shifts all other elements up one.

a = [ "b", "c", "d" ]
a.unshift("a") ["a", "b", "c", "d"]


Contents ^
Next >

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide"
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/)).

Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.

Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder.