Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
arrays
programming
data structures
list

How to work with arrays in Ruby

Educative Answers Team

In Ruby, arrays are ordered, integer-indexed, list-like collections of any kind of an object. Array index starts from 0 in Ruby, just like in C and Java. A negative array index is assumed to be relative from the end of the array.

svg viewer

Initializing arrays in Ruby

There are multiple ways to initialize arrays in Ruby as discussed below:

1. Using literal constructor

A new array can be created by using the literal constructor []. Have a look at the following array:

arr = [1, 2, 3, 4, 5]
puts "#{arr}"

2. Using new keyword

An array can also be created using new along with arguments.

  • Line 1: When no argument is given, an empty array of size 0 is created.

  • Line 3: When one integer argument is given, it is treated as size, and an empty array of that length is created.

  • Line 5: When another argument along with the integer argument is given, the array of the given length is created and filled with the second argument.

arr1 = Array.new()
puts "#{arr1}"
arr2 = Array.new(6)
puts "#{arr2}"
arr3 = Array.new(3, "Educative")
puts "#{arr3}"

3. Using a block

Arrays can also be created by using a block along with new. The array is then filled with the values produced by the block.

  • Line 1,2: This method can be used to fill the array with elements each of which depends on the element on the last index.

  • Line 3,4: Using this method, you can create multi-dimensional arrays, like the empty 4x4 array created in the example below.

arr1 = Array.new(5){|a| a = a * 3}
puts "#{arr1}"
arr2 = Array.new(4){Array.new(4)}
puts "#{arr2}"

Array access and other methods

Arrays in Ruby have many useful built-in methods.

  • at(int): Method to access an array element at the given index. Returns nil, if no element is present at the index, or the index is out of bounds.
  • fetch(int, string): Method to access an array element. Raises out of bounds error if index, which is the first argument, is out of range. Alternatively, if a second parameter is given, it gets printed.
  • length / size: Returns an integer specifying the length of the array.
  • first: Returns the first element of the array.
  • last: Returns the last element of the array.
  • take(int): Returns first n elements from the array, as specified by the passed integer.
  • drop(int): Returns last length-n elements from the array, as specified by the passed integer
  • empty?: Returns a boolean value after checking if an array contains any elements in it.
  • include?(ele): Returns a boolean specifying whether the passed ele exists in the array or not.
  • push(ele) / << ele: Adds element to the end of the array.
  • unshift(ele): Adds ele to the beginning of the array.
  • insert(int, ele ... ): Adds element(s) starting from the given integer index.
  • pop: Removes and returns the last element.
  • shift: Removes and returns the first element.
  • delete_at(int): Removes an element at the given integer index
arr1 = Array.new(10){|a| a = a * 3}     # Create 10 element array
puts "#{arr1}"                          # print the array
puts arr1.at(-1)                        # print element at index 1
puts arr1.fetch(5)                      # print element at index 5
puts arr1.fetch(100, "oops: OutOfRange")# print element at index 100
puts arr1.length                        # print array length
puts arr1.size                          # print array length
puts arr1.first                         # print first element of array
puts arr1.last                          # print last element of array
puts "#{arr1.take(5)}"                  # print first 5 element of array
puts "#{arr1.drop(5)}"                  # print last 5 elements of array
puts arr1.empty?                        # check if array is empty
puts arr1.include?(9)                   # check if array includes 9
puts "#{arr1.push(100)}"                # add 100 to the end of array
puts "#{arr1 << 100}"                   # add 100 to the end of array
puts "#{arr1.unshift(-1)}"              # add -1 to the start of array
puts "#{arr1.insert(3, 4, 5)}"          # add 4 and 5 at index 3 of array
puts "#{arr1.pop}"                      # delete and return last element 
puts "#{arr1.shift}"                    # delete and return first element 
puts "#{arr1.delete_at(-1)}"            # delete and return last element
puts "#{arr1}"                          # print the final array

RELATED TAGS

ruby
arrays
programming
data structures
list
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring