Programming Ruby
The Pragmatic Programmer's Guide
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"
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!"]
Returns a new array based on the
arr with
all
nil elements removed.
[ "a", nil, "b", nil, "c", nil ].compact
サ
["a", "b", "c"]
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
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:
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:
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"
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]
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")
サ
"a000円000円b000円000円c000円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"]
Returns a new array using
arr's elements in reverse order.
[ "a", "b", "c" ].reverse
サ
["c", "b", "a"]
[ 1 ].reverse
サ
[1]
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
Same as
Array#each
, but traverses
arr in reverse order.
a = [ "a", "b", "c" ]
a.reverse_each {|x| print x, " " }
produces:
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"]
Returns
arr.
Synonym for
Array#to_a
.
Returns
arr
.join.
[ "a", "e", "i", "o" ].to_s
サ
"aeio"
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"]
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.