Ruby Array(Array)

A Ruby array is an ordered set of integer indexes for any object. Each element in the array is associated with an index and can be retrieved through an index.

The index of the array starts at 0, which is the same as in C or Java. A negative number is counted relative to the end of the array, that is, the index is -1 for the last element of the array, -2 is the second-to-last element of the array, and so on.

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

Ruby arrays do not need to be sized, and Ruby arrays grow automatically when you add elements to an array.

Create an array

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

names = Array.new

You can set the size of the array while creating the array:

names = Array.new( 20)

Array names is 20 elements in size or length. 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 # return 20 puts names.length # return 20

The above example runs the output as:


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


#!/usr/bin/ruby names = Array.new(4, "mac") puts "#{names}"

The above example runs the output as:

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

You can also use blocks with new, each of which is populated with calculations in the block:


#!/usr/bin/ruby nums = Array< Span class="hl-code">.new(10) { | e| e = e * 2 } puts "#{nums}"

The above example runs the output as:

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

Arrays have another method, [], as follows:

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 takes only a single parameter, which uses a range as a parameter to create an array of numbers:


#!/usr/bin/ruby digits = Array(0..9) puts "#{digits}"

The above example runs the output as:

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

Array built-in method

We need to have an instance of the Array object to call the Array method. Here's how to create an Array object instance:

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

This will restore another exhibit populated with the given article. Presently, utilizing the made item, we can call any of the accessible strategies. For example:


#!/usr/canister/ruby digits = Array(0..9) num = digits.at(6) puts "#{num}"

The above precedent runs the yield as:


The following is an open cluster technique (accepting array is an Array object):

serial numbermethod & description
1array & other_array
Returns another exhibit containing the components normal to both clusters, with no redundancy.
2array * int [or] cluster * str
restores another exhibit made by linking a duplicate of self 's int . With the String contention, it is proportionate to self.join(str).
3array + other_array
Returns another cluster made by linking two exhibits to deliver a third exhibit.
4array - other_array
Returns another cluster that expels things from different exhibits that show up in other_array A duplicate.
5str <=> other_str
Compare str with other_str and return - 1 (under), 0 (equivalent) or 1 (more noteworthy than). The examination is case touchy.
6array | other_array
Returns another exhibit by adding other_array to cluster, expelling copies.
7array << obj
Appends the offered item to the finish of the exhibit. This articulation restores the cluster itself, so a few augmentations can be consolidated.
8array <=> other_array
If the exhibit is not exactly, equivalent to, or more noteworthy than other_array, return a whole number (- 1, 0 or +1).
9array == other_array
If two clusters contain a similar number of components, and every component relates to another exhibit The components are equivalent (as per Object.==), at that point the two exhibits are equivalent.
10array[index] [or] array[start, length] [or]
Array[range] [or] array.slice(index) [or]
Array.slice(start, length) [or] array.slice(range)

Returns a component with list index or comes back from start A subarray of length components, or a subarray determined by range. A negative file begins tallying from the finish of the cluster (- 1 is the last component). Returns nil if index (or begin file) is out of range.
11array[index] = obj [or]
Array[start, length] = obj or an_array or nil [or]
Array[range] = obj or an_array or nil

Set the component with record index, or supplant it from start until length a subarray of components, or supplant the subarray determined by range. In the event that the file is more noteworthy than the present limit of the cluster, the exhibit develops consequently. Negative lists begin checking from the finish of the exhibit. Addition a component if length is zero. In the event that nil is utilized in the second or third structure, the component is expelled from self.
12array.abbrev(pattern = nil)
Calculate a contracted arrangement of shortenings for strings in self . In the event that you pass an example or a string, possibly consider the situation when the string matches the example or begins with the string.
Search for an exhibit whose components are additionally clusters, utilizing obj.== to put obj with each The principal component of the cluster is thought about. Returns the first containing exhibit on the off chance that it matches, or nil if no match is found.
Returns a component listed to file. A negative file begins checking from the finish of self. Returns nil if the file is out of range.
Remove all components from the exhibit.
16array.collect { |item| square } [or]
Array.map { |item| square }

Calls block once for every component in self. Make another cluster containing the qualities ​​returned by the square.
17array.collect! { |item| square } [or]
Array.map! { |item| square }

Invoke block once for every component in self, supplanting the component with block The esteem returned.
Returns a duplicate of self and evacuates all nil component.
Remove all nil components from the exhibit. Returns nil if there is no change.
Add components from other_array to self.
21array.delete(obj) [or]
Array.delete(obj) { square }

Remove things equivalent to obj from self. On the off chance that no correspondence is found, nil is returned. On the off chance that no fairness is found and the discretionary code block is given, the aftereffect of block is returned.
Remove the component at the predefined index and return it. On the off chance that the record is out of range, nil is returned.
23array.delete_if { |item| square }
When block is valid, erase Each component of self.
24array.each { |item| square }
Invoke once for every component in self i>block, passing this component as a parameter.
25array.each_index { |index| square }
Same as Array#each, yet passing index of the component > as opposed to passing the component itself.
Returns genuine if the exhibit itself does not contain a component.
If array and other are Returns valid if a similar article, or two clusters, have a similar substance.
28array.fetch(index) [or]
Array.fetch(index, default) [or]
Array.fetch(index) { |index| square }

Try to restore the component at position index. On the off chance that index is outside the exhibit, the main structure will toss a IndexError special case, and the second structure will return default, the third structure It will restore the estimation of the index go to block. Negative index tallies from the finish of the cluster.
29array.fill(obj) [or]
Array.fill(obj, begin [, length]) [or]
Array.fill(obj, run) [or]
Array.fill { |index| square } [or]
Array.fill(start [, length] ) { |index| square } [or]
Array.fill(range) { |index| square }

The three picked segments of self are obj. Starting with nil is indistinguishable to zero. The length of nil is equivalent to self.length. The last three structures are populated with the estimation of the square show. block is experienced a level out rundown with each segment being filled.
30array.first [or]

restores the principal component of the cluster or the first n components. On the off chance that the cluster is unfilled, the main structure returns nil, and the second structure restores a vacant exhibit.
Returns another exhibit, which is a one-dimensional smoothed cluster (recursive).
Flatten array. Returns nil if there is no change. (Exhibits don't contain subarrays.)
If genuine if array is solidified (or incidentally solidified when arranging) .
Calculate the hash code of the exhibit. Two clusters with a similar substance will have a similar hash code.
If self contains obj , return genuine, generally return false.
Returns the self of the primary article equivalent to obj >index. Returns nil if no match is found.
37array.indexes(i1, i2, ... iN) [or]
Array.indices(i1, i2, ... iN)

This technique is deplored in the most recent form of Ruby, so use Array#values_at.
38array.indices(i1, i2, ... iN) [or]
Array.indexes(i1, i2, ... iN)

This technique is censured in the most recent form of Ruby, so use Array#values_at.
39array.insert(index, obj...)
Before the given index component Insert the given esteem and file can be negative.
Create a printable adaptation of the exhibit.
restores a string by changing over every component of the cluster to a string, And made utilizing sep partition.
42array.last [or] array.last(n)
restores the last component of self. In the event that the exhibit is empty, the principal structure returns nil.
Returns the quantity of components in self. May be zero.
44array.map { |item| square } [or]
Array.collect { |item| square }

Calls block once for every component of self. Make another cluster containing the qualities returned by the square.
45array.map! { |item| square } [or]
Array.collect! { |item| square }

Calls block once for every component of array, supplanting the component with the esteem returned by square.
Returns the quantity of non-nil components in self. May be zero.
Compresses the substance of the cluster into a parallel succession dependent on the guidelines in aTemplateString. Directions An, an, and Z can be trailed by a number demonstrating the width of the subsequent field. The rest of the guidelines can likewise have a number demonstrating the quantity of exhibit components to be changed over. On the off chance that the number is an indicator (*), all residual cluster components will be changed over. Any guidance can be trailed by an underscore (_) showing that the predefined type utilizes the local size of the basic stage, generally a stage autonomous size is utilized. Spaces in the layout string are overlooked.
Remove the last component from array and return it. Returns nil if array is unfilled.
49array.push(obj, ...)
Appends the offered obj as far as possible of the exhibit. This articulation restores the cluster itself, so a few increases can be combined.
Search for a cluster whose components are likewise exhibits, utilizing == to put key Compare with the second component of each contained cluster. Returns the first containing cluster in the event that it matches.
51array.reject { |item| square }
Returns another cluster containing exhibit things when square isn't valid.
52array.reject! { |item| square }
Delete from array when square is genuine The component, if there is no change, returns nil. Comparable to Array#delete_if.
Replace the substance of array with other_array > The substance are truncated or extended as vital.
Returns another exhibit containing the cluster components in turn around request.
Reverse array.
56array.reverse_each {|item| square }
Same as Array#each, however with array switch.
Returns the file of the last article in cluster equivalent to obj. On the off chance that no match is found, nil is returned.
58array.select {|item| square }
calls a square that goes in continuous components from the cluster, restores an exhibit containing the square The component when the true esteem.
Returns the main component of self and evacuates the component (puts the various components move down one piece). Returns nil if the exhibit is vacant.
Returns the length of array (the quantity of components). A nom de plume 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 a component with a file of index or comes back from start until A subarray of length components, or a subarray determined by range. A negative list begins checking from the finish of the exhibit (- 1 is the last component). Returns nil if index (or begin file) is out of range.
62array.slice!(index) [or] array.slice!(start, length) [or]

Remove the index (length is discretionary) or range indicated component. Returns the erased article, subarray, or nil if index is out of range.
63array.sort [or] array.sort { | a,b | square }
Returns an arranged exhibit.
64array.sort! [or] array.sort! { | a,b | square }
Sort the exhibit.
Return self. Whenever approached a subclass of Array, changes over the get parameter to an Array object.
returns self.
Returns self.join.
Assume that self is a variety of clusters and replaces lines and segments.
Returns another exhibit, expelling copy esteems from array.
Remove copy components from self. On the off chance that there is no change (that is, no copies are discovered), at that point nil is returned.
71array.unshift(obj, ...)
Place the article before the cluster and move different components up one piece.
restores a cluster containing the self with the given selector(one or increasingly) comparing components. The selector can be a number list or range.
73array.zip(arg, ...) [or]
Array.zip(arg, ...){ | arr | square }

Convert any contention to an exhibit, at that point the array component compares to every parameter The components are blended.

Array pack directive

The adhering to table records the pressure directions for the strategy Array#pack.

@ Move to total position.
AASCII string (fill space, check is width).
aASCII string (loaded up with invalid, check is width).
BBit String (Descending)
bBit string (rising request).
CUnsigned characters.
c characters.
D, dDouble-exactness coasting point numbers, local arrangement.
EDouble-accuracy skimming point numbers, little-endian byte request.
e Single-accuracy drifting point numbers, little-endian byte request.
F, f Single-accuracy skimming point numbers, local configuration.
GDouble-exactness drifting point numbers, network(big-endian) byte request.
g Single-exactness gliding point numbers, network(big-endian) byte request.
HHexadecimal string (high request first).
hhexadecimal string (lower first).
IUnsigned number.
LUnsigned long.
M references printable, MI


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 above example runs the output as:

a b c

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.