English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Ruby arrays are ordered collections of objects with integer indices. Each element in an array is associated with an index and can be accessed by index.
The index of an array starts from 0, just like in C or Java. A negative index counts from the end of the array, meaning that the index of -1 Represents the last element of an array.-2 represents the second-to-last element in the array, 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; they will automatically grow when elements are added.
There are many ways to create or initialize an array. One way is through new Class method:
names = Array.new
You can set the size of the array while creating it:
names = Array.new(20)
array names The size or length is 20 elements. You can use the size or length method to return the size of the array:
#!/usr/bin/ruby names = Array.new(20) puts names.size # Returns 20 puts names.length # Returns 20
The output result of the above example is:
20 20
You can assign a value to each element in the array as shown below:
#!/usr/bin/ruby names = Array.new(4, "mac") puts "#{names}"
The output result 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 calculation in the block:
#!/usr/bin/ruby nums = Array.new(10) { |e| e = e * 2 } puts "#{nums}"
The output result of the above example is:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
The array also has another method, [], as shown below:
nums = Array.[](1, 2, 3, 4,5)
Another form of array creation is shown below:
nums = Array[1, 2, 3, 4,5]
In the Ruby core module, there can be an Array method that accepts a single parameter, which creates a numeric array using a range as the parameter:
#!/usr/bin/ruby digits = Array(0..9) puts "#{digits}"
The output result of the above example is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We need an example of an Array object to call Array methods. Below are the ways to create an Array object:
Array.[](...) [or] Array[...] [or] [...]
This will return a new array filled with the given object. Now, using the created object, we can call any available method. For example:
#!/usr/bin/ruby digits = Array(0..9) num = digits.at(6) puts "#{num}"
The output result of the above example is:
6
Below are the common array methods (assuming array is an Array object):
Serial number | method & description |
---|---|
1 | array & other_array Returns a new array containing the common elements of the two arrays without repetition. |
2 | array * int [or] array * str Return a new array that is created by connecting the int copy of self. With a String parameter, it is equivalent to self.join(str). |
3 | array + other_array Return a new array that is created by connecting two arrays to produce a third array. |
4 | array - other_array Return a new array that is a copy of the initial array with items removed that appear in other_array. |
5 | str <=> other_str Compare str with other_str and return -1)(less), 0(equal) or 1)(greater). The comparison is case-sensitive. |
6 | array | other_array Remove duplicates by adding other_array to array and return a new array. |
7 | array << obj Attach the given object to the end of the array. This expression returns the array itself, so several attachments can be chained together. |
8 | array <=> other_array If the array is less than, equal to, or greater than other_array, return an integer (-1, 0 or +1) |
9 | array == other_array If two arrays contain the same number of elements and each element is equal to the corresponding element in the other array (based on Object.==), then the two arrays are equal. |
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 element, or returns from start starting from length elements' sub-array, or returns range the specified sub-array. Negative indices start counting from the end of the array(-1 is the last element). If index(or start index)is out of range, then 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 set the index to index the element, or replace from start starting from length a sub-array of elements, or replace range the specified sub-array. If the index is greater than the current capacity of the array, the array will automatically grow. Negative indices start counting from the end of the array. If length If zero is specified, an element is inserted. If the second or third form is used with nilthen from self Remove an element. |
12 | array.abbrev(pattern = nil) array.collect! { |item| block } self The explicit abbreviation set for string calculations. If a pattern or a string is passed, only consider the cases when the string matches the pattern or starts with the string. |
13 | array.assoc(obj) Search an array whose elements are also arrays, compare obj.== with the first element of each contained array. If a match is found, return the first containing array, if no match is found, then return nil. |
14 | array.at(index) Returns the element at index self Counting from the end. If the index is out of range, then returns nil. |
15 | array.clear Remove all elements from the array. |
16 | array.collect { |item| block } [or] array.map { |item| block } array.collect! { |item| block } self of each element. is called once for each elementarray.collect { |item| block } |
17 | array.collect! { |item| block } [or] array.map! { |item| block } array.collect! { |item| block } self of each element. is called once for each elementand replace the element with is called once for each element is returned. All |
18 | array.compact returns self A copy of nil elements. |
19 | array.compact! Remove all nil elements. If there is no change, then returns nil. |
20 | array.concat(other_array) Appending elements from self . |
21 | array.delete(obj) [or] array.delete(obj) { block } from self from obj of the item. If no matching item is found, then returns nil. If no matching item is found and optional code is provided is called once for each elementReturns is called once for each element The result. |
22 | array.delete_at(index) specified element, and returns index at the specified index, and returns the element. If the index is out of range, then returns nil. |
23 | array.delete_if { |item| block } When is called once for each element Deletes if self of each element. |
24 | Called once for each element. array.collect! { |item| block } self of each element. is called once for each elementPass the element as an argument. |
25 | Called once for each element in Similar to Array#each, but passes the element as an argument. indexInstead of passing the element itself. |
26 | array.empty? Returns true if the array itself does not contain any elements. |
27 | array.eql?(other) If array and other Returns true if it is the same object, or if two arrays contain the same content. |
28 | array.fetch(index) [or] array.fetch(index, default) [or] array.fetch(index) { |index| block } an attempt is made to return the position index element. If index is outside the array, the first form will throw IndexError exception, the second form will return default, the third form will return the called is called once for each element passed index values. Negative values index Counting 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 elements selected as obj. With nil The start is equivalent to zero.nil is equivalent to self.length. The last three forms use the value of the blockFillarray.is called once for each element Pass the absolute index of each filled element. |
30 | array.first [or] array.first(n) Returns the first element or the first n elements. If the array is empty, the first form returns nil, the second form returns an empty array. |
31 | array.flatten Returns a new array, which is a one-dimensional flattened array (recursive). |
32 | array.flatten! reverses array Flatten. If there is no change, it returns nil. (The array does not contain subarrays.) |
33 | array.frozen? If array is frozen (or temporarily frozen when sorted), it returns true. |
34 | array.hash Calculates the hash code of the array. Two arrays with the same content will have the same hash code. |
35 | array.include?(obj) If self contains obj, it returns true, otherwise it returns false. |
36 | array.index(obj) returns self the first object equal to obj in index. If no match is found, it returns nil. |
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 instead. |
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 instead. |
39 | array.insert(index, obj...) Given index Inserts the given value before the element at the specified index, which can be a negative value. |
40 | array.inspect array.inspect |
41 | Creates a printable version of the array. array.join(sep=$,) Returns a string by converting each array element to a string and using sep |
42 | is created by separating with. returns self array.last [or] array.last(n)The last element of the array. If the array isis empty nil. |
43 | If the first form is used returns self array.length |
44 | The number of elements in the array. It may be zero. array.map { |item| block } [or] array.collect! { |item| block } self is is called once for each elementarray.collect { |item| block } |
45 | Creates a new array containing the values returned by the block. array.map! { |item| block } [or] array.collect! { |item| block } array is is called once for each elementReplaces the element with the value returned by block. The block |
46 | array.nitems returns self non-The number of nil elements. It may be zero. |
47 | array.pack(aTemplateString) Compresses the content of the array into a binary sequence based on the instructions in aTemplateString. Instructions A, a, and Z can be followed by a number representing the width of the result field. The remaining instructions can also have a number representing the number of array elements to convert. If the number is an asterisk (**All remaining array elements will be converted. Any instruction can be followed by an underscore (_) to specify that the size should use the local size of the underlying platform, otherwise, it uses a consistent size independent of the platform. Spaces are ignored in template strings. |
48 | array.pop from array Removes the last element from the middle, and returns that element. If array Returns if empty nil. |
49 | array.push(obj, ...) Appends the given obj to the end of the array. The expression returns the array itself, so multiple appends can be chained together. |
50 | array.rassoc(key) Searches an array whose elements are also arrays, using == to key Compares with each second element of the included arrays. If a match is found, returns the first included array. |
51 | array.reject { |item| block } Returns a new array containing the array items for which block is not true. |
52 | array.reject! { |item| block } When block is true, from array Removes elements, returning the array if no changes were made. nilEquivalent to Array#delete_if. |
53 | array.replace(other_array) reverses array contents to other_array contents, truncating or expanding as necessary. |
54 | array.reverse returns a new array containing the elements of the array in reverse order. |
55 | array.reverse! reverses array reverses the array. |
56 | array.reverse_each {|item| block } is the same as Array#each, but reverses array reverses the array. |
57 | array.rindex(obj) returns the index of the last object in array that is equal to obj. If no match is found, then returns nil. |
58 | array.select {|item| block } invokes a block passed continuous elements from the array, returning an array containing the elements returned by the block true when the element has the value. |
59 | array.shift returns self the first element, and removes it (shifting all other elements down by one). If the array is empty, then returns nil. |
60 | array.size returns array length (number of elements). length is an alias. |
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 element, or returns from start starting from length elements' sub-array, or returns range the specified sub-array. Negative indices start counting from the end of the array(-1 is the last element). If index(or start index)is out of range, then returns nil. |
62 | array.slice!(index) [or] array.slice!(start, length) [or] array.slice!(range) deletes index(length is optional)or range the specified element. Returns the removed object, sub-array, if index returns 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. |
65 | array.to_a returns selfIf in Array When called on a subclass, the received parameter is converted into 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, and swaps rows and columns. |
69 | array.uniq returns a new array that removes array duplicate values. |
70 | array.uniq! from self removes duplicate elements. If there is no change (i.e., no duplicates are found), then return nil. |
71 | array.unshift(obj, ...) puts the object at the front of the array, and moves other elements up one position. |
72 | array.values_at(selector,...) returns an array containing self with the given selectora (one or more) corresponding elements. The selector can be an integer index or a range. |
73 | array.zip(arg, ...) [or] array.zip(arg, ...){ | arr | block } convert any parameters to an array, then array elements are merged with the corresponding elements in each parameter. |
The following table lists the compression instructions for the Array#pack method.
instruction | description |
---|---|
@ | move to an absolute position. |
A | ASCII string (filled with space, count is width). |
a | ASCII string (filled with null, count is width). |
B | bit string (descending order) |
b | bit string (ascending order). |
C | unsigned character. |
c | character. |
D, d | double-precision floating-point number, native format. |
E | double-precision floating-point number, little-endian Byte Order. |
e | single-precision floating-point number, little-endian Byte Order. |
F, f | single-precision floating-point number, native format. |
G | double-precision floating-point number, network(big-endian) byte order. |
g | single-precision floating-point number, network(big-endian) byte order. |
H | hexadecimal string (high-order first). |
h | hexadecimal string (low-order first). |
I | unsigned integer. |
i | integer. |
L | unsigned long. |
l | Long. |
M | reference printable, MIME encoded. |
m | Base64 encoded string. |
N | Long, network(big-endian) byte order. |
n | Short, network(big-endian) byte order. |
P | points to a structure (fixed-length string). |
p | points to a null-terminated string. |
Q, q | 64 bit digits. |
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 | Skip one byte forward. |
x | Null Byte. |
Z | Same as a, except null will be added *. |
Try the following example, compress various data.
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 output result of the above example is:
a b c abc ABC