Ruby Arrays (Array)
A Ruby array is an ordered, integer-indexed collection of any objects. Each element in the array is associated with an index and can be retrieved by that index.
Array indices start at 0, as in C or Java. A negative index counts from the end of the array, i.e., an index of -1 means the last element, -2 means the second-to-last element, and so on.
Ruby arrays can store objects such as String, Integer, Fixnum, Hash, Symbol, and even other Array objects.
Ruby arrays do not need a specified size; when elements are added, the array grows automatically.
Creating an Array
There are several ways to create or initialize an array. One way is through the new class method:
names
=
Array
.
new
You can set the size of the array at the same time you create it:
names
=
Array
.
new
(
20
)
arrays names The size or length is 20 elements. You can use the size or length method to return the array's size:
Example
!/usr/bin/ruby
names
=
Array
.
new
(
20
)
puts
names
.
size
Returns 20
puts
names
.
length
Returns 20
Try it »
The above example produces the following output:
20
20
You can assign a value to each element in the array, as follows:
Example
!/usr/bin/ruby
names
=
Array
.
new
(
4
,
"
mac
"
)
puts
"
#{names}
"
Try it »
The above example produces the following output:
["mac", "mac", "mac", "mac"]
You can also use a block with new, where each element is filled with the result of the block's computation:
Example
!/usr/bin/ruby
nums
=
Array
.
new
(
10
)
{ |
e
|
e
=
e
2
}
puts
"
#{nums}
"
Try it »
The above example produces the following output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Arrays have another method, [], as follows:
nums
=
Array
.
[
]
(
1
,
2
,
3
,
4
,
5
)
Another form of array creation is shown below:
nums
=
Array
[
1
,
2
,
3
,
4
,
5
]
In Ruby's core module, there can be an Array method that takes a single argument, using a range as the argument to create an array of numbers:
Example
!/usr/bin/ruby
digits
=
Array
(
.9
)
puts
"
#{digits}
"
The above example produces the following output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array built-in methods
We need an instance of an Array object to call Array methods. Here is how to create an Array object instance:
Array
.
[
]
(
...
)
[
or
]
Array
[
...
]
[
or
]
[
...
]
This returns a new array filled with the given object. Now, using the created object, we can call any available method. For example:
Example
!/usr/bin/ruby
digits
=
Array
(
.9
)
num
=
digits
.
at
(
6
)
puts
"
#{num}
"
The above example produces the following output:
6
The following are common array methods (assuming array is an Array object):
| No. | Method & Description |
|---|---|
| 1 | array & other_array |
| Returns a new array containing the elements common to both arrays, without duplicates. | |
| 2 | array * int [or] array * str |
| Returns a new array created by concatenating int copies of self. With a String argument, it is equivalent to self.join(str). | |
| 3 | array + other_array |
| Returns a new array created by concatenating two arrays to produce a third array. | |
| 4 | array - other_array |
| Returns a new array that is a copy of the original array with items appearing in other_array removed. | |
| 5 | str <=> other_str |
| Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is case-sensitive. | |
| 6 | array | other_array |
| By adding other_array to array and removing duplicates, returns a new array. | |
| 7 | array << obj |
| Appends the given object to the end of the array. The expression returns the array itself, so several appends can be chained together. | |
| 8 | array <=> other_array |
| Returns an integer (-1, 0, or +1) if the array is less than, equal to, or greater than other_array. | |
| 9 | array == other_array |
| Two arrays are equal if they contain the same number of elements and each element is equal to the corresponding element in the other array (according to Object.==). | |
| 10 | **array[index] [or] array[start, length] [or] |
array[range] [or] array.slice(index) [or]
array.slice(start, length) [or] array.slice(range)**
Returns the element at index index , or returns a subarray from start up to length elements, or returns the range specified subarray. Negative indices count from the end of the array (-1 is the last element). If index(or the start index) is out of range, returns nil。 | | 11 | array[index] = obj [or]
array[start, length] = obj or an_array or nil [or]
array[range] = obj or an_array or nil
Sets the element at index index , or replaces the subarray from start up to length for elements, or replaces the range specified subarray. If the index is greater than the array's current capacity, the array grows automatically. Negative indices count from the end of the array. If length is zero, inserts the element. If a block is used in the second or third form, nil, then from self removes elements. | | 12 | array.abbrev(pattern = nil)
is self computes the set of unambiguous abbreviations for the strings in . If a pattern or a string is passed, only strings matching the pattern or starting with that string are considered. | | 13 | array.assoc(obj)
Searches an array whose elements are also arrays, comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches, or returns nil if no match is found. nil。 | | 14 | array.at(index)
Returns the element at index. A negative index counts from self the end of . If the index is out of range, returns nil. | | 15 | array.clear
Removes all elements from the array. | | 16 | array.collect { |item| block } [or]
array.map { |item| block }
is self calls once for each element in block. Creates a new array containing the values returned by the block. | | 17 | array.collect! { |item| block } [or]
array.map! { |item| block }
is self calls once for each element in block, replacing the element with the value returned by block the block. | | 18 | array.compact
Return self a copy of , with all nil elements removed. | | 19 | array.compact!
Removes all nil elements from the array. Returns nil if no changes were made. nil。 | | 20 | array.concat(other_array)
Appends the elements of other_array to self . | | 21 | array.delete(obj) [or]
array.delete(obj) { block }
From the self Deletes items equal to obj items from . Returns nil if no equal item is found. nilIf no equal item is found and an optional code block, return block block is given, returns its result. | | 22 | array.delete_at(index)
Deletes the element at the specified index index and returns it. If index is out of range, returns nil。 | | 23 | array.delete_if { |item| block }
When block When the block returns true, deletes self each element. | | 24 | array.each { |item| block }
is self calls once for each element in block, passing the element as an argument. | | 25 | array.each_index { |index| block }
Same as Array#each, but passes the element's indexinstead of the element itself. | | 26 | array.empty?
Returns true if the array contains no elements. | | 27 | array.eql?(other)
If both the array and other are the same object, or two arrays have the same content, returns true. | | 28 | array.fetch(index) [or]
array.fetch(index, default) [or]
array.fetch(index) { |index| block }
Attempts to return the element at position index . If the index index is outside the array, the first form raises an IndexError exception, the second form returns default, and the third form returns the result of calling block with the index passed index in. A negative index index counts from the end of the array. | | 29 | array.fill(obj) [or]
array.fill(obj, start [, length]) [or]
array.fill(obj, range) [or]
array.fill { |index| block } [or]
array.fill(start [, length] ) { |index| block } [or]
array.fill(range) { |index| block }
The first three forms set self the selected elements of to obj. Starting with nil is equivalent to zero.nil The length of is equivalent to self.length. The last three forms use the block's valueFillarray.block passed along with the absolute index of each element being filled. | | 30 | array.first [or]
array.first(n)
Returns the first element of the array, or the first n elements. If the array is empty, the first form returns nil, and the second form returns an empty array. | | 31 | array.flatten
Returns a new array that is a one-dimensional flattened version of the array (recursively). | | 32 | array.flatten!
Puts the array Flattens in place. Returns nil if no changes were made. nil. (The array contains no subarrays.) | | 33 | array.frozen?
If both the array is frozen (or temporarily frozen during sorting), returns true. | | 34 | array.hash
Computes the hash code of the array. Two arrays with the same content have the same hash code. | | 35 | array.include?(obj)
If both the self contains obj, returns true; otherwise returns false. | | 36 | array.index(obj)
Return self the index of the first object in equal to obj index. Returns nil if no match is found. nil。 | | 37 | array.indexes(i1, i2, ... iN) [or]
array.indices(i1, i2, ... iN)
This method is deprecated in the latest versions of Ruby, so use Array#values_at instead. | | 38 | array.indices(i1, i2, ... iN) [or]
array.indexes(i1, i2, ... iN)
This method is deprecated in the latest versions of Ruby, so use Array#values_at instead. | | 39 | array.insert(index, obj...)
Inserts the given values before the element at the given index index. The index may be negative. | | 40 | array.inspect
Creates a printable version of the array. | | 41 | array.join(sep=$,)
Returns a string created by converting each element of the array to a string and using sep as a separator. | | 42 | array.last [or] array.last(n)
Return self the last element of . If the array isnull, the first form returns nil。 | | 43 | array.length
Return self the number of elements in . May be zero. | | 44 | array.map { |item| block } [or]
array.collect { |item| block }
is self calls once for each element of block. Creates a new array containing the values returned by the block. | | 45 | array.map! { |item| block } [or]
array.collect! { |item| block }
is array calls once for each element of block, replacing the element with the value returned by the block. | | 46 | array.nitems
Return self the number of non-nil elements in . May be zero. | | 47 | array.pack(aTemplateString)
Packs the contents of the array into a binary sequence according to the directives in aTemplateString. Directives A, a, and Z may be followed by a number indicating the width of the resulting field. The remaining directives may also take a number indicating how many array elements to convert. If the number is an asterisk (*), all remaining array elements are converted. Any directive may be followed by an underscore (_), indicating that the specified type uses the underlying platform's native size; otherwise a platform-independent consistent size is used. Spaces in the template string are ignored. | | 48 | array.pop
From the array Removes the last element from and returns it. If array is empty, returns nil。 | | 49 | array.push(obj, ...)
Appends the given obj to the end of the array. The expression returns the array itself, so several appends can be chained together. | | 50 | array.rassoc(key)
Searches an array whose elements are also arrays, using == to compare key with the second element of each contained array. If a match is found, returns the first contained array. | | 51 | array.reject { |item| block }
Returns a new array containing the items for which the block is not true. | | 52 | array.reject! { |item| block }
When the block is true, deletes elements from array . Returns nil if no changes were made. nil. Equivalent to Array#delete_if. | | 53 | array.replace(other_array)
Puts the array Replaces the contents of with other_array , truncating or expanding as necessary. | | 54 | array.reverse
Returns a new array containing the elements in reverse order. | | 55 | array.reverse!
Puts the array Reverses in place. array.reverse_each {|item| block }
Same as Array#each, but traverses array in reverse. | | 57 | array.rindex(obj)
Returns the index of the last object in array equal to obj. Returns nil if no match is found. nil。 | | 58 | array.select {|item| block }
Calls the block passing in successive elements from the array, returning an array containing those elements for which the block returns a true true value. | | 59 | array.shift
Return self the first element and returns it, removing it (shifting all other elements down by one). Returns nil if the array is empty. nil。 | | 60 | array.size
Return array the length (number of elements) of . An alias for length. | | 61 | array.slice(index) [or] array.slice(start, length) [or]
array.slice(range) [or] array[index] [or]
array[start, length] [or] array[range]
Returns the element at index index , or returns a subarray from start up to length elements, or returns the range specified subarray. Negative indices count from the end of the array (-1 is the last element). If index(or the start index) is out of range, returns nil。 | | 62 | array.slice!(index) [or] array.slice!(start, length) [or]
array.slice!(range)
Delete index(length is optional) or range the specified elements. Returns the deleted object or subarray, or index if out of range. nil。 | | 63 | array.sort [or] array.sort { | a,b | block }
Returns a sorted array. | | 64 | array.sort! [or] array.sort! { | a,b | block }
Sorts the array in place. array.to_a
Return self. If called on a Array subclass of , the receiver is converted to an Array object. | | 66 | array.to_ary
Returns self. | | 67 | array.to_s
Returns self.join. | | 68 | array.transpose
Assuming self is an array of arrays, transposes rows and columns. | | 69 | array.uniq
Returns a new array with duplicate values removed from array . | | 70 | array.uniq!
From the self Removes duplicate elements from . Returns nil if no changes were made (that is, no duplicates were found). nil。 | | 71 | array.unshift(obj, ...)
Prepends an object to the front of the array, shifting other elements up by one. | | 72 | array.values_at(selector,...)
Returns an array containing the elements of self corresponding to the given selector(one or more). The selector can be an integer index or a range. | | 73 | array.zip(arg, ...) [or]
array.zip(arg, ...){ | arr | block }
Converts any arguments to arrays, then merges the elements of array with the corresponding elements in each argument. |
Array pack directives
The following table lists the packing directives for the Array#pack method.
| Instruction | Description |
|---|---|
| @ | Moves to an absolute position. |
| A | ASCII string (padded with spaces; count is the width). |
| a | ASCII string (padded with nulls; count is the width). |
| B | Bit string (descending order) |
| b | Bit string (ascending order). |
| C | Unsigned character. |
| c | Character. |
| D, d | Double-precision float, native format. |
| E | Double-precision float, little-endian byte order. |
| e | Single-precision float, little-endian byte order. |
| F, 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 | Hexadecimal string (high byte first). |
| h | Hexadecimal string (low byte first). |
| I | Unsigned integer. |
| i | Integer. |
| L | Unsigned long. |
| l | Long。 |
| M | Quoted-printable, MIME encoding. |
| 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. |
| Q, q | 64-bit number. |
| S | Unsigned short. |
| s | Short。 |
| U | UTF-8。 |
| u | UU-encoded string. |
| V | Long, little-endian byte order. |
| v | Short, little-endian byte order. |
| w | BER-compressed integer \fnm. |
| X | Skips backward one byte. |
| x | Null byte. |
| Z | Same as a, except that nulls are padded with *. |
Example
Try the following examples to pack various kinds of data.
Example
a
=
[
"
a
"
,
"
b
"
,
"
c
"
]
n
=
[
65
,
66
,
67
]
puts
a
.
pack
(
"
A3A3A3
"
)
=> "a b c "
puts
a
.
pack
(
"
a3a3a3
"
)
=> "a\000\000b\000\000c\000\000"
puts
n
.
pack
(
"
ccc
"
)
=> "ABC"
The above example produces the following output:
a b c
abc
ABC