YouTip LogoYouTip

Ruby Array

Ruby arrays are ordered, integer-indexed collections of any objects. Each element in an array is associated with and referred to by an index.

Array indexing starts at 0, as in C or Java. A negative index is assumed 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 hold objects such as String, Integer, Fixnum, Hash, Symbol, or even other Array objects.

Ruby arrays do not need to be of a fixed size. When you add elements to an array, it will automatically grow.

There are several ways to create or initialize an array. One way is by using the new class method:

names = Array.new

You can set the size of an array at the time of creation:

names = Array.new(20)

The size or length of the array names is 20 elements. You can return the size or length of an array by using the size or length methods:

Example

names = Array.new(20)
puts names.size
puts names.length

Try it yourself Β»

This will produce the following result:

20
20

You can assign a value to each element in the array as follows:

Example

names = Array.new(4, "mac")
puts "#{names}"

Try it yourself Β»

This will produce the following result:

["mac", "mac", "mac", "mac"]

You can also use a block with new, where each element in the array is populated with the result of the block:

Example

nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"

Try it yourself Β»

This will produce the following result:

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

There is another form of array, [], as follows:

nums = Array.[](1, 2, 3, 4, 5)

Another form of array creation is as follows:

nums = Array[1, 2, 3, 4, 5]

There is a method in the Ruby core module that takes a single argument, the Array method, which uses a range as an argument to create a numeric array:

Example

digits = Array(0..9)
puts "#{digits}"

This will produce the following result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We need to have an instance of an Array object to call the Array method. Here is the way to create an instance of the Array object:

Array.[](...)

Array[...]

[...]

This returns a new array populated with the given objects. Now, using the created object, we can call any available method. For example:

Example

digits = Array(0..9)
num = digits.at(6)
puts "#{num}"

This will produce the following result:

6

Below are the public array methods (assuming array is an Array object):

No. Method & Description
1 array & other_array
Returns a new array containing unique elements common to the two arrays, with no duplicates.
2 array * int array * str
Returns a new array which is the concatenation of self repeated int times. With a String argument, it is equivalent to self.join(str).
3 array + other_array
Returns a new array which is the concatenation of self and other_array.
4 array - other_array
Returns a new array which is a copy of the original array, removing any items that also appear in other_array.
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 joining array with other_array, removing duplicates.
7 array << obj
Pushes the given object onto the end of array. This expression returns the array itself, so several appends may 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 array[start, length] array array.slice(index) array.slice(start, length) array.slice(range)
Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count from the end of the array (-1 is the last element). Returns nil if the index (or start index) is out of range.
11 array = obj array[start, length] = obj or an_array or nil array = obj or an_array or nil
Sets the element at index, or replaces a subarray starting at start and continuing for length elements, or replaces a subarray specified by range. If the index is greater than the current capacity of the array, the array will grow automatically. Negative indices count from the end of the array. If length is zero, it inserts elements. If nil is used in the second or third form, it deletes elements from self.
12 array.abbrev(pattern = nil)
Computes a set of unambiguous abbreviations for the strings in self. If a pattern or a string is passed, only those strings matching the pattern or starting with the string are considered.
13 array.assoc(obj)
Searches through an array whose elements are also arrays, comparing obj with the first element of each contained array using obj.==. Returns the first contained array that matches. Returns nil if no match is found.
14 array.at(index)
Returns the element at 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 array.
16 array.collect { |item| block } array.map { |item| block }
Calls block once for each element in self. Creates a new array containing the values returned by the block.
17 array.collect! { |item| block } array.map! { |item| block }
Calls 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 nil elements removed.
19 array.compact!
Removes all nil elements from array. Returns nil if no changes were made.
20 array.concat(other_array)
Appends the elements in other_array to self.
21 array.delete(obj) array.delete(obj) { block }
Deletes items from self that are equal to obj. Returns nil if no matches are found. If the optional code block is given and no match is found, it returns the result of the block.
22 array.delete_at(index)
Deletes the element at the specified index, returning that element (or nil if the index is out of range).
23 array.delete_if { |item| block }
Deletes every element of self for which block evaluates to true.
24 array.each { |item| block }
Calls block once for each element in self, passing that element as a parameter.
25 array.each_index { |index| block }
Same as Array#each, but passes the index of the element instead of the element itself.
26 array.empty?
Returns true if the array itself contains no elements.
27 array.eql?(other)
Returns true if array and other are the same object or are both arrays with the same content.
28 array.fetch(index) array.fetch(index, default) array.fetch(index) { |index| block }
Tries to return the element at position index. If index is outside the array bounds, the first form raises an IndexError, the second form returns default, and the third form returns the value of invoking the block, passing the index. Negative values of index count from the end of the array.
29 array.fill(obj) array.fill(obj, start [, length]) array.fill(obj, range) array.fill { |index| block } array.fill(start [, length] ) { |index| block } array.fill(range) { |index| block }
The first three forms set the selected elements of self to obj. A start of nil is equivalent to zero. A length of nil is equivalent to self.length. The last three forms _fill_ the array with the value of the block. The block is passed the absolute index of each element to be filled.
30 array.first array.first(n)
Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, the second form returns an empty array.
31 array.flatten
Returns a new array that is a one-dimensional flattening of this array (recursively).
32 array.flatten!
Flattens array in place. Returns nil if no changes were made (the array contained no subarrays).
33 array.frozen?
Returns true if array is frozen (or temporarily frozen while being sorted).
34 array.hash
Computes a hash-code for the array. Two arrays with the same content will have the same hash code.
35 array.include?(obj)
Returns true if self contains obj, otherwise returns false.
36 array.index(obj)
Returns the _index_ of the first object in self that is == to obj. Returns nil if no match is found.
37 array.indexes(i1, i2, ... iN) array.indices(i1, i2, ... iN)
This method is deprecated in newer versions of Ruby. Use Array#values_at instead.
38 array.indices(i1, i2, ... iN) array.indexes(i1, i2, ... iN)
This method is deprecated in newer versions of Ruby. Use Array#values_at instead.
39 array.insert(index, obj...)
Inserts the given values before the element at the given index. index can be negative.
40 array.inspect
Creates a printable version of array.
41 array.join(sep=$,)
Returns a string created by converting each element of the array to a string, separated by sep.
42 array.last array.last(n)
Returns the last element(s) of self. If the array is _empty_, the first form returns nil.
43 array.length
Returns the number of elements in self. May be zero.
44 array.map { |item| block } array.collect { |item| block }
Calls block once for each element in self. Creates a new array containing the values returned by the block.
45 array.map! { |item| block } array.collect! { |item| block }
Calls block once for each element in array, replacing the element with the value returned by block.
46 array.nitems
Returns the number of non-nil elements in self. May be zero.
47 array.pack(aTemplateString)
Packs the contents of array into a binary sequence according to the directives in aTemplateString. Directives A, a, and Z may be followed by a count, which indicates the width of the result field. The remaining directives may also have a count, which indicates the number of array elements to convert. If the count is an asterisk (*), all remaining array elements will be converted. Any directive may be followed by an underscore (_) to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the template string.
48 array.pop
Removes the last element from array and returns it (or nil if the array is empty).
49 array.push(obj, ...)
Pushes the given object(s) onto the end of array. This expression returns the array itself, so several appends may be chained together.
50 array.rassoc(key)
Searches through an array whose elements are also arrays, comparing key with the second element of each contained array using ==. Returns the first contained array that matches.
51 array.reject { |item| block }
Returns a new array containing the items from array for which the block is not true.
52 array.reject! { |item| block }
Deletes elements from array for which the block is true. Returns nil if no changes were made. Equivalent to Array#delete_if.
53 array.replace(other_array)
Replaces the contents of array with the contents of other_array, truncating or expanding as necessary.
54 array.reverse
Returns a new array containing the elements of array in reverse order.
55 array.reverse!
Reverses array in place.
56 array.reverse_each {|item| block }
Same as Array#each, but traverses array in reverse order.
57 array.rindex(obj)
Returns the index of the last object in array == to obj. Returns nil if no match is found.
58 array.select {|item| block }
Calls the block passing in successive elements from array, returning an array containing those elements for which the block returns a true value.
59 array.shift
Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty.
60 array.size
Returns the length of array (number of elements). Alias for length.
61 array.slice(index) array.slice(start, length) array.slice(range) array array[start, length] array
Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count from the end of the array (-1 is the last element). Returns nil if the index (or start index) is out of range.
62 array.slice!(index) array.slice!(start, length) array.slice!(range)
Deletes the element(s) given by index (optionally with a length) or by range. Returns the deleted object, subarray, or nil if index is out of range.
63 array.sort array.sort { | a,b | block }
Returns a sorted array.
64 array.sort! array.sort! { | a,b | block }
Sorts array in place.
65 array.to_a
Returns self. If called on a subclass of Array, converts the receiver to an Array object.
66 array.to_ary
Returns self.
67 array.to_s
Returns self.join.
68 array.transpose
Assumes that self is an array of arrays and transposes the rows and columns.
69 array.uniq
Returns a new array by removing duplicate values from array.
70 array.uniq!
Removes duplicate elements from self. Returns nil if no changes were made (that is, no duplicates were found).
71 array.unshift(obj, ...)
Prepends objects to the front of array, moving other elements up one.
72 array.values_at(selector,...)
Returns an array containing the elements in self corresponding to the given selector(s). The selectors may be either integer indices or ranges.
73 array.zip(arg, ...) array.zip(arg, ...){ | arr | block }
Converts any arguments to arrays, then merges elements of array with corresponding elements from each argument.

The following table lists the packing directives for the method Array#pack.

Directive Description
@ Moves to an absolute position.
A ASCII string (space padding, count is the width).
a ASCII string (null padding, count is the width).
B Bit string (MSB first).
b Bit string (LSB first).
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 int.
i Int.
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 Back up a byte.
x Null byte.
Z Same as a, except that null is added with *.

Example

Try the following example to pack various data.

Example

a = ["a", "b", "c"]
n = [65, 66, 67]
puts a.pack("A3A3A3")
puts a.pack("a3a3a3")
puts n.pack("ccc")

This will produce the following result:

a   b   c   
abc 
ABC
← Dom Obj DialogRuby String β†’