Ruby Arrays
Ruby arrays are ordered collections of objects. They can hold objects like integer, number, hash, string, symbol or any other array.
Its indexing starts with 0. The negative index starts with -1 from the end of the array. For example, -1 indicates last element of the array and 0 indicates first element of the array.
Creating Ruby Arrays
A Ruby array is created in many ways.
- Using literal constructor []
- Using new class method
Using literal construct []
A Ruby array is constructed using literal constructor []. A single array can contain different type of objects.
For example, following array contains an integer, floating number and a string.
Output:
Using new class method
A Ruby array is constructed by calling ::new method with zero, one or more than one arguments.
Syntax:
To set the size of an array,
Syntax:
Here, we have mentioned that array size is of 10 elements.
To know the size of an array, either size or length method is used.
Example:
Output:
Example:
Output:
Accessing Array Elements
Ruby array elements can be accessed using #[] method. You can pass one or more than one arguments or even a range of arguments.
Example:
Output:
at method
To access a particular element, at method can also be used.
Example:
Output:
slice method
The slice method works similar to #[] method.
fetch method
The fetch method is used to provide a default value error for out of array range indices.
Example:
Output:
Example:
Output:
first and last method
The first and last method will return first and last element of an array respectively.
Example:
Output:
take method
The take method returns the first n elements of an array.
Example:
Output:
drop method
The drop method is the opposite of take method. It returns elements after n elements have been dropped.
Example:
Output:
Adding Items to Array
Ruby array elements can be added in different ways.
- push or <<
- unshift
- insert
push or <<
Using push or <<, items can be added at the end of an array.
Example:
Output:
unshift
Using unshift, a new element can be added at the beginning of an array.
Example:
Output:
insert
Using insert, a new element can be added at any position in an array. Here, first we need to mention the index number at which we want to position the element.
Example:
Output:
Removing Items from Array
Ruby array elements can be removed in different ways.
- pop
- shift
- delete
- uniq
pop
Using pop, items can be removed from the end of an array. It returns the removed item.
Example:
Output:
shift
Using shift, items can be removed from the start of an array. It returns the removed item.
Example:
Output:
delete
Using delete, items can be removed from anywhere in an array. It returns the removed item.
Example:
Output:
uniq
Using uniq, duplicate elements can be removed from an array. It returns the remaining array.
Example:
Output: