Ruby Arrays
Ruby arrays are ordered, integer-indexed collections of any object. Each element in an array is associated with an index and can be accessed via that index.
Array indexing starts at 0, as in C or Java. A negative index is counted relative to the end of the array. That is, an index of -1 indicates the last element of the array, -2 indicates 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 to specify a size. When elements are added to an array, Ruby arrays automatically grow.
Creating Arrays
There are multiple ways to create or initialize an array. One way is through thenewclass method:
You can set the size of the array while creating it:
The arraynameshas a size or length of 20 elements. You can use the size or length method to return the array's size:
Example
Try it »
The output of the above example is:
20 20
You can assign values to each element of the array, as shown below:
The output of the above example is:
["mac", "mac", "mac", "mac"]
You can also use a block with new, filling each element with the result of the block's calculation:
The output of the above example is:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
There is also another method for arrays, [], as shown below:
Another form of array creation is as follows:
In the Ruby core module, there can be an Array method that takes only a single argument. This method uses a range as an argument to create a numeric array:
Example
The output of the above example is:
[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. The following is how to create an instance of an Array object:
This returns a new array filled with the given objects. Now, using the created object, we can call any available method. For example:
Example
The output of the above example is:
6
The following are the public array methods (assumingarrayis an Array object):
| No. | Method & Description |
|---|---|
| 1 | array & other_array Returns a new array containing the elements common to both arrays, with no duplicates. |
| 2 | array * int [or] array * str Returns a new array created by concatenating int copies of self. With a String argument, 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 Returns a new array by adding other_array to the array and removing duplicates. |
| 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 indexindex, or returns the subarray starting from startstartup to lengthlengthelements, or returns therangerange-specified subarray. Negative indexes count from the end of the array (-1 is the last element). If indexindex(or the starting index) is out of range, returnsnil。 |
| 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 indexindex, or replaces the subarray from startstartup to lengthlengthelements, or replaces therangerange-specified subarray. If the index is greater than the array's current capacity, the array automatically grows. Negative indexes count from the end of the array. If lengthlengthis zero, elements are inserted. If rangenilis used in the second or third form, then fromselfdelete elements. |
| 12 | array.abbrev(pattern = nil) isselfThe strings in it compute an explicit abbreviation set. If a pattern or a string is passed, only cases where the string matches the pattern or starts with the string are considered. |
| 13 | array.assoc(obj) Searches an array whose elements are also arrays, using obj.== to compare obj with the first element of each contained array. If a match is found, returns the first contained array; if no match is found, returnsnil。 |
| 14 | array.at(index) Returns the element at index. A negative index counts from theselfend of the array. Returns nil if the index is out of range. |
| 15 | array.clear Removes all elements from the array. |
| 16 | array.collect { |item| block } [or] array.map { |item| block } isselfCalls the block once for each element inblock. Creates a new array containing the values returned by the block. |
| 17 | array.collect! { |item| block } [or] array.map! { |item| block } isselfCalls the block once for each element inblock, replacing the element withblockthe value returned by the block. |
| 18 | array.compact Returns a copy ofselfwith allnilelements removed. |
| 19 | array.compact! Removes allnilelements from the array. If there is no change, returnsnil。 |
| 20 | array.concat(other_array) Appends the elements of other_array toself. |
| 21 | array.delete(obj) [or] array.delete(obj) { block } fromselfDeletes from the array the item equal toobjobj. If no equal item is found, returnsnil. If no equal item is found and an optional codeblockis given, returnsblockthe result of the block. |
| 22 | array.delete_at(index) Deletes the element at the specifiedindexindex and returns that element. If the index is out of range, returnsnil。 |
| 23 | array.delete_if { |item| block } Whenblockwhen it is true, deletesselfevery element of the array. |
| 24 | array.each { |item| block } isselfCalls the block once for each element inblock, passing the element as an argument. |
| 25 | array.each_index { |index| block } Same as Array#each, but passes the element'sindexindex instead of the element itself. |
| 26 | array.empty? Returns true if the array itself contains no elements. |
| 27 | array.eql?(other) Returns true ifarrayandotheris the same object, or if the two arrays have the same content. |
| 28 | array.fetch(index) [or] array.fetch(index, default) [or] array.fetch(index) { |index| block } Attempts to return the element at positionindex. Ifindexis outside the array, the first form throws anIndexErrorexception, the second form returnsdefault, and the third form returns the result of callingblockthe block withindexthe index as an argument. Negativeindexindexes count 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 setselfthe selected elements of self toobjobj. Anilstart of nil is equivalent to zero.nilThe length of nil is equivalent toself.lengththe length of self. The last three forms use the block's value to fillthearray.blockThe block is passed the absolute index of each element being filled. |
| 30 | array.first [or] array.first(n) Returns the first element or the firstnelements. If the array is empty, the first form returnsnil, and the second form returns an empty array. |
| 31 | array.flatten Returns a new array that is a one-dimensional flattened array (recursively). |
| 32 | array.flatten! holdarrayPerforms flattening. If there is no change, returnsnil. (The array does not contain subarrays.) |
| 33 | array.frozen? Returns true ifarrayis frozen (or temporarily frozen during sorting). |
| 34 | array.hash Computes the hash code for the array. Two arrays with the same content will have the same hash code. |
| 35 | array.include?(obj) Returns true ifselfcontainsobj, then returns true, otherwise false. |
| 36 | array.index(obj) Returns theselfindex of the first object equal to obj inindex. If no match is found, returnsnil。 |
| 37 | array.indexes(i1, i2, ... iN) [or] array.indices(i1, i2, ... iN) This method is deprecated in the latest version of Ruby, so please use Array#values_at. |
| 38 | array.indices(i1, i2, ... iN) [or] array.indexes(i1, i2, ... iN) This method is deprecated in the latest version of Ruby, so please use Array#values_at. |
| 39 | array.insert(index, obj...) at the givenindexindex, insert the given value before the element; index can be negative. |
| 40 | array.inspect Create a printable version of an array. |
| 41 | array.join(sep=$,) Returns a string created by converting each element of the array to a string and usingsepthe separator to join them. |
| 42 | array.last [or] array.last(n) Returnsselfthe last element of. If the array isEmpty, the first form returnsnil。 |
| 43 | array.length Returnsselfthe number of elements in. May be zero. |
| 44 | array.map { |item| block } [or] array.collect { |item| block } isselfcalled once for each element ofblock. Creates a new array containing the values returned by the block. |
| 45 | array.map! { |item| block } [or] array.collect! { |item| block } isarraycalled once for each element ofblock, replacing the element with the value returned by the block. |
| 46 | array.nitems Returnsselfthe 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 also may take a number indicating the number of array elements to convert. If the number is an asterisk (*), all remaining array elements will be converted. Any directive may be followed by an underscore (_) to indicate that the specified type uses the native size of the underlying platform; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the template string. |
| 48 | array.pop fromarrayRemoves the last element from and returns it. Ifarrayis empty, returnsnil。 |
| 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 comparekeywith 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 of the array for which the block is not true. |
| 52 | array.reject! { |item| block } When the block is true, deletes elements fromarray. If there is no change, returnsnil. Equivalent to Array#delete_if. |
| 53 | array.replace(other_array) holdarrayReplaces the contents of with the contents ofother_array, truncating or expanding if necessary. |
| 54 | array.reverse Returns a new array containing the elements of the array in reverse order. |
| 55 | array.reverse! holdarrayReverses it. |
| 56 | array.reverse_each {|item| block } Same as Array#each, butarrayiterates in reverse order. |
| 57 | array.rindex(obj) Returns the index of the last object in array equal to obj. If no match is found, returnsnil。 |
| 58 | array.select {|item| block } Calls the block with consecutive elements from the array; returns an array containing the elements for which the block returnstruea true value. |
| 59 | array.shift Returnsselfthe first element of and removes it (shifting all other elements down by one). If the array is empty, returnsnil。 |
| 60 | array.size Returnsarraythe length of (the number of elements). 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 indexindex, or returns a subarray starting atstartand continuing forlengthelements, or returns the subarray specified byrange. Negative indices count from the end of the array (-1 is the last element). Ifindex(or the start index) is out of range, returnsnil。 |
| 62 | array.slice!(index) [or] array.slice!(start, length) [or] array.slice!(range) Deletesindex(length is optional) orrangethe element(s) specified by. Returns the deleted object, subarray, or ifindexis out of range, returnsnil。 |
| 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. |
| 65 | array.to_a Returnsself. If called onArraya subclass of, converts the receiver to an Array object. |
| 66 | array.to_ary Returns self. |
| 67 | array.to_s Returns self.join. |
| 68 | array.transpose Assumes self is an array of arrays and transposes the rows and columns. |
| 69 | array.uniq Returns a new array witharrayduplicate values removed from. |
| 70 | array.uniq! fromselfRemoves duplicate elements from. If there is no change (that is, no duplicates are found), returnsnil。 |
| 71 | array.unshift(obj, ...) Prepends the object to the front of the array, moving other elements up by one. |
| 72 | array.values_at(selector,...) Returns an array containing the elements of self corresponding to the givenselectorselector(s). The selectors can be integer indices or ranges. |
| 73 | array.zip(arg, ...) [or] array.zip(arg, ...){ | arr | block } Converts any arguments to arrays, then mergesarrayelements of with corresponding elements from each argument. |
Array pack Directives
The following table lists the pack directives for the method Array#pack.
| Directive | Description |
|---|---|
| @ | 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, 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 | 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. |
| 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 back one byte. |
| x | Null byte. |
| Z | Same as a, except null is added with *. |
Example
Try the following example, packing various data.
Example
The output of the above example is:
a b c abc ABCOther extensions