English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby Arrays (Array)

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.

Creating an array

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:

Online Example

#!/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:

Online Example

#!/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:

Online Example

#!/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:

Online Example

#!/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]

Built-in array methods

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:

Online 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 numbermethod & description
1array & other_array
Returns a new array containing the common elements of the two arrays without repetition.
2array * 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).
3array + other_array
Return a new array that is created by connecting two arrays to produce a third array.
4array - other_array
Return a new array that is a copy of the initial array with items removed that appear in other_array.
5str <=> other_str
Compare str with other_str and return -1)(less), 0(equal) or 1)(greater). The comparison is case-sensitive.
6array | other_array
Remove duplicates by adding other_array to array and return a new array.
7array << obj
Attach the given object to the end of the array. This expression returns the array itself, so several attachments can be chained together.
8array <=> other_array
If the array is less than, equal to, or greater than other_array, return an integer (-1, 0 or +1)
9array == 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.
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 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.
11array[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.
12array.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.
13array.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.
14array.at(index)
Returns the element at index self Counting from the end. If the index is out of range, then returns nil.
15array.clear
Remove all elements from the array.
16array.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 }
17array.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
18array.compact
returns self A copy of nil elements.
19array.compact!
Remove all nil elements. If there is no change, then returns nil.
20array.concat(other_array)
Appending elements from self .
21array.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.
22array.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.
23array.delete_if { |item| block }
When is called once for each element Deletes if self of each element.
24Called once for each element.
array.collect! { |item| block } self of each element. is called once for each elementPass the element as an argument.
25Called once for each element in
Similar to Array#each, but passes the element as an argument. indexInstead of passing the element itself.
26array.empty?
Returns true if the array itself does not contain any elements.
27array.eql?(other)
If array and other Returns true if it is the same object, or if two arrays contain the same content.
28array.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.
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 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.
30array.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.
31array.flatten
Returns a new array, which is a one-dimensional flattened array (recursive).
32array.flatten!
reverses array Flatten. If there is no change, it returns nil. (The array does not contain subarrays.)
33array.frozen?
If array is frozen (or temporarily frozen when sorted), it returns true.
34array.hash
Calculates the hash code of the array. Two arrays with the same content will have the same hash code.
35array.include?(obj)
If self contains obj, it returns true, otherwise it returns false.
36array.index(obj)
returns self the first object equal to obj in index. If no match is found, it returns nil.
37array.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.
38array.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.
39array.insert(index, obj...)
Given index Inserts the given value before the element at the specified index, which can be a negative value.
40array.inspect
array.inspect
41Creates a printable version of the array.
array.join(sep=$,) Returns a string by converting each array element to a string and using sep
42is created by separating with.
returns self array.last [or] array.last(n)The last element of the array. If the array isis empty nil.
43If the first form is used
returns self array.length
44The 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 }
45Creates 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
46array.nitems
returns self non-The number of nil elements. It may be zero.
47array.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.
48array.pop
from array Removes the last element from the middle, and returns that element. If array Returns if empty nil.
49array.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.
50array.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.
51array.reject { |item| block }
Returns a new array containing the array items for which block is not true.
52array.reject! { |item| block }
When block is true, from array Removes elements, returning the array if no changes were made. nilEquivalent to Array#delete_if.
53array.replace(other_array)
reverses array contents to other_array contents, truncating or expanding as necessary.
54array.reverse
returns a new array containing the elements of the array in reverse order.
55array.reverse!
reverses array reverses the array.
56array.reverse_each {|item| block }
is the same as Array#each, but reverses array reverses the array.
57array.rindex(obj)
returns the index of the last object in array that is equal to obj. If no match is found, then returns nil.
58array.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.
59array.shift
returns self the first element, and removes it (shifting all other elements down by one). If the array is empty, then returns nil.
60array.size
returns array length (number of elements). length is an alias.
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 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.
62array.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.
63array.sort [or] array.sort { | a,b | block }
returns a sorted array.
64array.sort! [or] array.sort! { | a,b | block }
sorts the array.
65array.to_a
returns selfIf in Array When called on a subclass, the received parameter is converted into an Array object.
66array.to_ary
returns self.
67array.to_s
returns self.join.
68array.transpose
assuming self is an array of arrays, and swaps rows and columns.
69array.uniq
returns a new array that removes array duplicate values.
70array.uniq!
from self removes duplicate elements. If there is no change (i.e., no duplicates are found), then return nil.
71array.unshift(obj, ...)
puts the object at the front of the array, and moves other elements up one position.
72array.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.
73array.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.

Array pack instructions

The following table lists the compression instructions for the Array#pack method.

instructiondescription
@move to an absolute position.
AASCII string (filled with space, count is width).
aASCII string (filled with null, count is width).
Bbit string (descending order)
bbit string (ascending order).
Cunsigned character.
ccharacter.
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-order first).
hhexadecimal string (low-order first).
Iunsigned integer.
iinteger.
Lunsigned long.
lLong.
Mreference printable, MIME encoded.
mBase64 encoded string.
NLong, network(big-endian) byte order.
nShort, network(big-endian) byte order.
Ppoints to a structure (fixed-length string).
ppoints to a null-terminated string.
Q, q64 bit digits.
Sunsigned short.
sShort.
UUTF-8.
uUU Encoded String.
VLong, little-endian Byte Order.
vShort, little-endian Byte Order.
wBER Compressed Integer \fnm.
XSkip one byte forward.
xNull Byte.
ZSame as a, except null will be added *.

Online Example

Try the following example, compress various data.

Online 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 output result of the above example is:

a    b    c
abc
ABC