OneBite.Dev - Coding blog in a bite size

get the nth element of array in Ruby

Code snippet on how to get the nth element of array in Ruby

  # Define array
  arr = [1, 2, 3, 4, 5]
  # Get the 3rd element from array
  arr[2]

This code calculates the 3rd element of an array. First, the variable “arr” is defined with an array containing the numbers 1 to 5. Then, the expression “arr[2]” is used. The expression “arr[2]” accesses the 3rd element in the array (2 is the index, and indexes start at 0). This expression returns the value 3, which is the 3rd element in the original “arr” array.

ruby