Easy Tutorial
❮ Ruby Socket Programming Ruby Class ❯

Ruby Array

A Ruby array is an ordered collection of objects indexed by integer keys. Each element in the array is associated with an index and can be accessed by this index.

The indexing starts at 0, similar to C or Java. Negative indices count from the end of the array, where -1 indicates the last element, -2 the second-to-last element, and so on.

Ruby arrays can store objects such as String, Integer, Fixnum, Hash, Symbol, and even other Array objects.

Ruby arrays do not require a predefined size; they automatically grow as elements are added.

Creating Arrays

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

names = Array.new

You can set the size of the array when creating it:

names = Array.new(20)

The names array has a size or length of 20 elements. You can use the size or length method to return the array's size:

Example

#!/usr/bin/ruby

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

The output of the above example is:

20
20

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

Example

#!/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 a block with new, which fills each element with the result of the block:

Example

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

Another method for creating arrays is [], 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, there is an Array method that accepts a single argument, creating an array of numbers using a range as a parameter:

Example

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

Built-in Array Methods

We need an instance of an Array object to call Array methods. Here is how to create an instance of an Array object:

Array.[](...) [or] Array[...] [or] [...]

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

Example

#!/usr/bin/ruby

digits = Array(0..9)

num = digits.at(6)

puts "#{num}"

The output of the above example is:

6

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

No. Method & Description
1 array & other_array <br>Returns a new array containing elements common to the two arrays, without duplicates.
2 array * int [or] array * str <br>Returns a new array built by concatenating the int copies of self. With a String argument, equivalent to self.join(str).
3 array + other_array <br>Returns a new array built by concatenating the two arrays together to produce a third array.
4 array - other_array <br>Returns a new array that is a copy of the original array, removing any items that also appear in other_array.
5 str <=> other_str <br>Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is case-sensitive.
6 array | other_array <br>Returns a new array by joining other_array to array, removing duplicates.
7 array << obj <br>Appends the given object to the end of the array. This expression returns the array itself, so several appends may be chained together.
8 array <=> other_array <br>Returns an integer (-1, 0, or +1) if the array is less than, equal to, or greater than other_array.
9 array == other_array <br>Returns true if the two arrays contain the same number of elements and if each element is equal to the corresponding element in the other array.
10 array[index] [or] array[start, length] [or]<br>array[range] [or] array.slice(index) [or]<br>array.slice(start, length) [or] array.slice(range) <br>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 backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) is out of range.
11 array[index] = obj [or]<br>array[start, length] = obj or an_array or nil [or]<br>array[range] = obj or an_array or nil <br>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 array size, the array grows automatically. Negative indices count backward from the end of the array. If length is zero, inserts elements. Using nil in the second or third forms deletes elements from self.
12 array.abbrev(pattern = nil) <br>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) <br>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, or nil if no match is found.
14 array.at(index) <br>Returns the element at index. A negative index counts from the end of the array. Returns nil if the index is out of range.
15 array.clear <br>Removes all elements from the array.
16 array.collect { item block } [or]<br>array.map { item block } <br>Calls block once for each element in self, creating a new array containing the values returned by the block.
17 array.collect! { item block } [or]<br>array.map! { item block } <br>Calls block once for each element in self, replacing the element with the value returned by the block.
18 array.compact <br>Returns a copy of self with all nil elements removed.
19 array.compact! <br>Removes nil elements from the array. Returns nil if no changes were made.
20 array.concat(other_array) <br>Appends the elements of other_array to self.
21 array.delete(obj) [or] <br>array.delete(obj) { block } <br>Deletes items from self that are equal to obj. Returns nil if no matching item is found. If the optional code block is given and no matching item is found, returns the result of the block.
22 array.delete_at(index) <br>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 } <br>Deletes every element of self for which block evaluates to true.
24 array.each { item block } <br>Calls block once for each element in self, passing that element as a parameter.
25 array.each_index { index block } <br>Same as Array#each, but passes the index of the element instead of the element itself.
26 array.empty? <br>Returns true if the array contains no elements.
27 array.eql?(other) <br>Returns true if array and other are the same object or if both are arrays with the same content.
28 array.fetch(index) [or] <br>array.fetch(index, default) [or] <br>array.fetch(index) { index block } <br>Tries to return the element at position index. If the index is out of bounds, the first form raises an IndexError exception, the second form returns default, and the third form returns the value of the block, which is passed the index. Negative indices count backward from the end of the array.
29 array.fill(obj) [or]<br>array.fill(obj, start [, length]) [or]<br>array.fill(obj, range) [or]<br>array.fill { index block } [or]<br>array.fill(start [, length]) { index block } [or]<br>array.fill(range) { index block } <br>The first three forms set the selected elements of self to obj. A nil start is equivalent to zero. A nil length 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 [or] <br>array.first(n) <br>Returns the first element, or the first n elements, of the array. If the array is empty, the first form returns nil, and the second form returns an empty array.
31 array.flatten <br>Returns a new array that is a one-dimensional flattening of this array (recursively).
32 array.flatten! <br>Flattens array in place. Returns nil if no modifications were made. (The array does not contain sub-arrays.)
33 array.frozen? <br>Returns true if the array is frozen (or temporarily frozen while being sorted).
34 array.hash <br>Computes a hash code for the array. Two arrays with the same content will have the same hash code.
35 array.include?(obj) <br>Returns true if obj is present in self, otherwise returns false.
36 array.index(obj) <br>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) [or]<br>array.indices(i1, i2, ... iN) <br>This method is deprecated in the latest version of Ruby, so use Array#values_at instead.
38 array.indices(i1, i2, ... iN) [or]<br>array.indexes(i1, i2, ... iN) <br>This method is deprecated in the latest version of Ruby, so use Array#values_at instead.
39 array.insert(index, obj...) <br>Inserts the given values before the element with the given index (which may be negative).
40 array.inspect <br>Creates a printable version of the array.
41 array.join(sep=$,) <br>Returns a string created by converting each element of the array to a string, separated by sep.
42 array.last [or] array.last(n) <br>Returns the last element(s) of self. Returns nil if the array is empty.
43 array.length <br>Returns the number of elements in self. May be zero.
44 array.map { item block } [or]<br>array.collect { item block } <br>Calls block once for each element in self, creating a new array containing the values returned by the block.
45 array.map! { item block } [or]<br>array.collect! { item block } <br>Invokes the block once for each element of array, replacing the element with the value returned by the block.
46 array.nitems <br>Returns the number of non-nil elements in self. May be zero.
47 array.pack(aTemplateString) <br>Packs the contents of an array into a binary sequence according to the directives in aTemplateString.
48 array.pop <br>Removes the last element from array and returns it, or nil if the array is empty.
49 array.push(obj, ...) <br>Appends the given obj(s) to the end of this array. Returns the array itself, so several appends may be chained together.
50 array.rassoc(key) <br>Searches through the array whose elements are also arrays. Compares key with the second element of each contained array using ==. Returns the first contained array that matches.
51 array.reject { item block } <br>Returns a new array containing the items in self for which the block is not true.
52 array.reject! { item block } <br>Deletes elements from array for which the block is true, but returns nil if no changes were made. Equivalent to Array#delete_if.
53 array.replace(other_array) <br>Replaces the contents of array with the contents of other_array, truncating or expanding if necessary.
54 array.reverse <br>Returns a new array containing self's elements in reverse order.
55 array.reverse! <br>Reverses array in place.
56 array.reverse_each { item block } <br>Same as Array#each, but traverses array in reverse order.
57 array.rindex(obj) <br>Returns the index of the last object in array == to obj. Returns nil if no match is found.
58 array.select { item block } <br>Invokes 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 <br>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 <br>Returns the length of the array (number of elements). Alias for length.
61 array.slice(index) [or] array.slice(start, length) [or]<br>array.slice(range) [or] array[index] [or]<br>array[start, length] [or] array[range] <br>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 backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) is out of range.
62 array.slice!(index) [or] array.slice!(start, length) [or]<br>array.slice!(range) <br>Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object(s), subarray, or nil if the index is out of range.
63 array.sort [or] array.sort { a,b block } <br>Returns a new array created by sorting self.
64 array.sort! [or] array.sort! { a,b block } <br>Sorts self.
65 array.to_a <br>Returns self. If called on a subclass of Array, converts the receiver to an Array object.
66 array.to_ary <br>Returns self.
67 array.to_s <br>Returns self.join.
68 array.transpose <br>Assumes that self is an array of arrays and transposes the rows and columns.
69 array.uniq <br>Returns a new array by removing duplicate values in self.
70 array.uniq! <br>Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
71 array.unshift(obj, ...) <br>Prepends objects to the front of array, moving other elements upwards.
72 array.values_at(selector,...) <br>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, ...) [or] <br>array.zip(arg, ...){ arr block } <br>Converts any arguments to arrays, then merges elements of array with corresponding elements from each argument.

Array Pack Directives

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

Directive Description
@ Moves to absolute position.
A ASCII string (space padded, count is width).
a ASCII string (null padded, count is width).
B Bit string (descending bit order).
b Bit string (ascending bit order).
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 integer.
i Integer.
L Unsigned long.
l Long.
M Quoted printable, MIME encoding (see RFC2045).
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.
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.

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"

Output:

a  b  c
abc
ABC
❮ Ruby Socket Programming Ruby Class ❯