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 numberMethod & Description
1array & other_array
Return a new array containing the common elements in the two arrays without duplication.
2array * 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).
3array + other_array
Returns a new array created by concatenating two arrays to produce a third array of.
4array - other_array
Returns a new array that is removed from the initial array in other_array A copy of the item that appears.
5str <=> other_str
Compare str with other_str and return -1 (less than), 0 (equal to) or 1 (greater than). Comparisons are case-sensitive.
6array | other_array
By adding other_array to array, remove duplicates and return a new array.
7array << obj
Appends the given object to the end of the array. The expression returns the array itself, so several additions can be chained together.
8array <=> other_array
If the array is less than, equal to, or greater than other_array, returns an integer (- 1, 0 or +1).
9array == 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.
10array[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.
11array[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.
12array.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.
13array.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.
14array.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.
15array.clear
Removes all elements from the array.
16array.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.
17array.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.
18array.compact
Returns a copy of self with all removed nil element.
19array.compact!
Removes all nil elements from the array. If there are no changes, return nil.
20array.concat(other_array)
Append the elements in other_array to self.
21array.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.
22array.delete_at(index)
Delete the element at the specified index and return the element. If index is out of range, nil is returned.
23array.delete_if { |item| block }
When block is true, delete Each element of self.
24array.each { |item| block }
Call block once for each element in self, passing that element as argument.
25array.each_index { |index| block }
Same as Array#each, but passes the of the element index instead of passing the element itself.
26array.empty?
Returns true if the array itself contains no elements.
27array.eql?(other)
If array and other If they are the same object, or the two arrays have the same content, return true.
28array.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.
29array.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.
30array.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.
31array.flatten
Returns a new array, which is a one-dimensional flattened array (recursively ).
32array.flatten!
Flatten array. If there are no changes, return nil. (The array contains no subarrays.)
33array.frozen?
If array is frozen (or temporarily frozen during sorting), it returns true.
34array.hash
Calculate the hash code of an array. Two arrays with the same contents will have the same hash code.
35array.include?(obj)
If self contains obj, returns true, otherwise returns false.
36array.index(obj)
Returns the first object in self that is equal to obj The index. Returns nil if no match is found.
37array.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.
38array.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.
39array.insert(index, obj...)
At the given index Insert the given value before the element, index can be a negative value.
40array.inspect
Creates a printable version of an array.
41array.join(sep=$,)
Returns a string by converting each element of the array is a string and is created using sep delimiters.
42array.last [or] array.last(n)
returns the last of self an element. The first form returns nil if the array is empty.
43array.length
Returns the number of elements in self. Possibly zero.
44array.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.
45array.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.
46array.nitems
Returns the number of non-nil elements in self. Possibly zero.
47array.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.
48array.pop
Removes the last element from array and returns that element . Returns nil if array is empty.
49array.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.
50array.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.
51array.reject { |item| block }
Returns a new array containing the array items when block is not true.
52array.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.
53array.replace(other_array)
Replace the contents of array with other_array The content of will be truncated or expanded when necessary.
54array.reverse
Returns a new array containing array elements arranged in reverse order.
55array.reverse!
Reverse array.
56array.reverse_each {|item| block }
is the same as Array#each, but array Perform reversal.
57array.rindex(obj)
Returns the index of the last object in array equal to obj. If no match is found, nil is returned.
58array.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.
59array.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.
60array.size
Returns the length (number of elements) of array. Alias ​​for length.
61array.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.
62array.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.
63array.sort [or] array.sort { | a,b | block }
Returns a sorted array .
64array.sort! [or] array.sort! { | a,b | block }
Sort the array Sort.
65array.to_a
returns self. If called on a subclass of Array, the received parameter is converted to an Array object.
66array.to_ary
Return self.
67array.to_s
Return self.join.
68array.transpose
Assume self is an array of arrays, with rows and columns transposed.
69array.uniq
Returns a new array with duplicates removed from array value.
70array.uniq!
Remove duplicate elements from self. If there are no changes (that is, no duplicates were found), nil is returned.
71array.unshift(obj, ...)
Put the object in front of the array and other elements Move one position.
72array.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.
73array.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.

CommandDescription
@Move to an absolute position.
AASCII string (padded with space, count is the width).
aASCII string (padded with null, count is width).
B digit string (descending order)
b digit string (ascending order).
CUnsigned character.
c characters.
D, dDouble precision floating point number, native format.
EDouble-precision floating point number, little-endian byte order.
eSingle-precision floating point number, little-endian byte order.
F, fSingle precision floating point number, native format.
GDouble-precision floating point number, network (big-endian) byte order.
gSingle-precision floating point number, network (big-endian) byte order.
HHexadecimal string (high endian).
hHexadecimal string (little endian).
IUnsigned integer.
iInteger.
LUnsigned long.
lLong.
M Quote printable, MIME encoded.
mBase64 encoded string.
NLong, network (big-endian) byte order.
nShort, network (big-endian) byte order.
P points to a structure (fixed length string).
p points to a null-terminated string.
Q, q64 digits.
SUnsigned short.
sShort.
UUTF-8.
uUU encoded string.
VLong, little-endian byte order.
vShort, little-endian byte order.
wBER compressed integer \fnm.
X Skip one byte backward.
xNull 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")   #=> "a
a  b  c
abc
ABC
0rrreee0brrreee0rrreee0crrreee0rrreee0" puts n.pack("ccc")      #=> "ABC"

The output result of the above example is:

rrreee