Ruby array (Array)
A Ruby array is an ordered integer-indexed collection of any object. Each element in the array is associated with an index and can be retrieved through the index.
Array indexes start at 0, just like in C or Java. A negative index counts relative to the end of the array, that is, an index of -1 represents the last element in the 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 have a specified size. Ruby arrays grow automatically when elements are added to the array.
Creating Arrays
There are many ways to create or initialize arrays. One way is through the new class method:
names = Array.new
You can set the size of the array while creating it:
names = Array.new(20)
arraynames of 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 # 返回 20 puts names.length # 返回 20
The output result of the above example is:
20 20
You can give each element in the array Element assignment, as shown below:
#!/usr/bin/ruby names = Array.new(4, "mac") puts "#{names}"
The output of the above example is:
["mac", "mac", "mac", "mac"]
You can also use blocks with new, each element Use the calculation results in the block to fill:
#!/usr/bin/ruby nums = Array.new(10) { |e| e = e * 2 } puts "#{nums}"
The output of the above example is:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
There is another method for arrays, [], As shown below:
nums = Array.[](1, 2, 3, 4,5)
Another form of array creation is as follows:
nums = Array[1, 2, 3, 4,5]
In the Ruby core module, you can have an Array method that only receives a single parameter, which uses a range Create an array of numbers as a parameter:
#!/usr/bin/ruby digits = Array(0..9) puts "#{digits}"
The output of the above example is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array built-in method
We need an instance of the Array object to call Array method. Here's how to create an instance of an Array object:
Array.[](...) [or] Array[...] [or] [...]
This will return a new array populated with the given object. Now, using the created object, we can call any of the available methods. For example:
#!/usr/bin/ruby digits = Array(0..9) num = digits.at(6) puts "#{num}"
The output result of the above example is:
6
The following are the public array methods (assuming array is an Array object):
Serial number | Method & Description |
---|---|
1 | array & other_array Return a new array containing the common elements in the two arrays without duplication. |
2 | array * int [or] array * str Returns a new array, the new array is connected to the int of self Copy created. With String parameter, equivalent to self.join(str). |
3 | array + other_array Returns a new array created by concatenating two arrays to produce a third array of. |
4 | array - other_array Returns a new array that is removed from the initial array in other_array A copy of the item that appears. |
5 | str <=> other_str Compare str with other_str and return -1 (less than), 0 (equal to) or 1 (greater than). Comparisons are case-sensitive. |
6 | array | other_array By adding other_array to array, remove duplicates and return a new array. |
7 | array << obj Appends the given object to the end of the array. The expression returns the array itself, so several additions can be chained together. |
8 | array <=> other_array If the array is less than, equal to, or greater than other_array, returns an integer (- 1, 0 or +1). |
9 | array == other_array If two arrays contain the same number of elements, and each element is different from the other If the corresponding elements in the arrays are equal (according to 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 with index index, or returns the element from start Starts a subarray up to length elements, or returns a subarray specified by range. Negative indexes count from the end of the array (-1 is the last element). If index (or starting index) is out of range, nil is returned. |
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 a subarray starting at start up to length elements, or replacing a subarray specified by range array. If the index is greater than the current capacity of the array, the array will automatically grow. Negative indexes count from the end of the array. If length is zero, the element is inserted. If nil is used in the second or third form, the element is removed from self. |
12 | array.abbrev(pattern = nil) is calculated explicitly for the string in self a collection of abbreviations. If you pass a pattern or a string, only cases where the string matches the pattern or starts with that string are considered. |
13 | array.assoc(obj) Search for an array whose elements are also arrays, use obj.== to replace obj Compares to the first element of each contained array. Returns the first containing array if a match is found, or nil if no match is found. |
14 | array.at(index) Returns the element with index index. A negative index counts from the end of self. 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 } Call block once for each element in self. Create a new array containing the values returned by block. |
17 | array.collect! { |item| block } [or] array.map! { |item| block } Call block once for each element in self, replacing the element with the value returned by block. |
18 | array.compact Returns a copy of self with all removed nil element. |
19 | array.compact! Removes all nil elements from the array. If there are no changes, return nil. |
20 | array.concat(other_array) Append the elements in other_array to self. |
21 | array.delete(obj) [or] array.delete(obj) { block } From Remove items equal to obj from self. If no equality is found, nil is returned. If no equality is found and the optional code block is given, the result of block is returned. |
22 | array.delete_at(index) Delete the element at the specified index and return the element. If index is out of range, nil is returned. |
23 | array.delete_if { |item| block } When block is true, delete Each element of self. |
24 | array.each { |item| block } Call block once for each element in self, passing that element as argument. |
25 | array.each_index { |index| block } Same as Array#each, but passes the of the element index instead of passing the element itself. |
26 | array.empty? Returns true if the array itself contains no elements. |
27 | array.eql?(other) If array and other If they are the same object, or the two arrays have the same content, return true. |
28 | array.fetch(index) [or] array.fetch(index, default) [or] array. fetch(index) { |index| block } Try to return the element at position index. If index is outside the array, the first form will throw an IndexError exception, the second form will return default, and the third form will return the calling block Pass in the value of index. Negative 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 previous three forms set the selected element of self to obj. Starting with nil is equivalent to zero. The length of nil is equivalent to self.length. The last three forms fill the array with the block's value . block Passed 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, which is a one-dimensional flattened array (recursively ). |
32 | array.flatten! Flatten array. If there are no changes, return nil. (The array contains no subarrays.) |
33 | array.frozen? If array is frozen (or temporarily frozen during sorting), it returns true. |
34 | array.hash Calculate the hash code of an array. Two arrays with the same contents will have the same hash code. |
35 | array.include?(obj) If self contains obj, returns true, otherwise returns false. |
36 | array.index(obj) Returns the first object in self that is equal to obj The index. Returns nil if no match is found. |
37 | array.indexes(i1, i2, ... iN) [or] array.indices(i1, i2, . ..iN) This method is deprecated in recent 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 recent versions of Ruby, so use Array#values_at instead. |
39 | array.insert(index, obj...) At the given index Insert the given value before the element, index can be a negative value. |
40 | array.inspect Creates a printable version of an array. |
41 | array.join(sep=$,) Returns a string by converting each element of the array is a string and is created using sep delimiters. |
42 | array.last [or] array.last(n) returns the last of self an element. The first form returns nil if the array is empty. |
43 | array.length Returns the number of elements in self. Possibly zero. |
44 | array.map { |item| block } [or] array.collect { |item| block } Call block once for each element of self. Create a new array containing the values returned by block. |
45 | array.map! { |item| block } [or] array.collect! { |item| block } Call block once for each element of array, replacing the element with the value returned by block. |
46 | array.nitems Returns the number of non-nil elements in self. Possibly zero. |
47 | array.pack(aTemplateString) According to the instructions in aTemplateString, compress the contents of the array into a binary sequence. Instructions A, a, and Z can be followed by a number indicating the width of the result field. The remaining instructions can also have a number indicating the number of array elements to be converted. If the number is an asterisk (*), all remaining array elements will be converted. Any directive may be followed by an underscore (_), indicating that the specified type uses the native size of the underlying platform, otherwise a consistent platform-independent size is used. White spaces are ignored in template strings. |
48 | array.pop Removes the last element from array and returns that element . Returns nil if array is empty. |
49 | array.push(obj, ...) Appends the given obj to the end of the array. The expression returns the array itself, so several additions can be chained together. |
50 | array.rassoc(key) Search for an array whose elements are also arrays, use == to key is compared to the second element of each contained array. If there is a match then the first containing array is returned. |
51 | array.reject { |item| block } Returns a new array containing the array items when block is not true. |
52 | array.reject! { |item| block } When block is true, from array Delete the element and return nil if there are no changes. Equivalent to Array#delete_if. |
53 | array.replace(other_array) Replace the contents of array with other_array The content of will be truncated or expanded when necessary. |
54 | array.reverse Returns a new array containing array elements arranged in reverse order. |
55 | array.reverse! Reverse array. |
56 | array.reverse_each {|item| block } is the same as Array#each, but array Perform reversal. |
57 | array.rindex(obj) Returns the index of the last object in array equal to obj. If no match is found, nil is returned. |
58 | array.select {|item| block } Call the block that passes in consecutive elements from the array and return an array , containing elements when the block returns a true value. |
59 | array.shift Returns the first element of self and removes it (Move all other elements down one position). If the array is empty, nil is returned. |
60 | array.size Returns the length (number of elements) of array. 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 with index index, or returns the element from start Starts a subarray up to length elements, or returns a subarray specified by range. Negative indexes count from the end of the array (-1 is the last element). If index (or starting index) is out of range, nil is returned. |
62 | array.slice!(index) [or] array.slice!(start, length) [or] array.slice !(range) Delete elements specified by index (length is optional) or range. Returns the deleted object, subarray, or nil if index is out of range. |
63 | array.sort [or] array.sort { | a,b | block } Returns a sorted array . |
64 | array.sort! [or] array.sort! { | a,b | block } Sort the array Sort. |
65 | array.to_a returns self. If called on a subclass of Array, the received parameter is converted to an Array object. |
66 | array.to_ary Return self. |
67 | array.to_s Return self.join. |
68 | array.transpose Assume self is an array of arrays, with rows and columns transposed. |
69 | array.uniq Returns a new array with duplicates removed from array value. |
70 | array.uniq! Remove duplicate elements from self. If there are no changes (that is, no duplicates were found), nil is returned. |
71 | array.unshift(obj, ...) Put the object in front of the array and other elements Move one position. |
72 | array.values_at(selector,...) Returns an array containing self with the given selector (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 parameter to an array, and then merge the elements of array with the corresponding elements in each parameter. |
Array pack command
The following table lists the compression instructions for the method Array#pack.
Command | Description |
---|---|
@ | Move to an absolute position. |
A | ASCII string (padded with space, count is the width). |
a | ASCII string (padded with null, count is width). |
B | digit string (descending order) |
b | digit string (ascending order). |
C | Unsigned character. |
c | characters. |
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 endian). |
h | Hexadecimal string (little endian). |
I | Unsigned integer. |
i | Integer. |
L | Unsigned long. |
l | Long. |
M | Quote 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 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 backward. |
x | Null byte. |
Z | Same as a, except null will be appended with *. |
Examples
Try the following examples to compress various data.
a = [ "a", "b", "c" ] n = [ 65, 66, 67 ] puts a.pack("A3A3A3") #=> "a b c " puts a.pack("a3a3a3") #=> "aa b c abc ABC0rrreee0brrreee0rrreee0crrreee0rrreee0" puts n.pack("ccc") #=> "ABC"
The output result of the above example is:
rrreee