OneBite.Dev - Coding blog in a bite size

extract a sub-array from an array in Ruby

Code snippet on how to extract a sub-array from an array in Ruby

  original_array = [1, 2, 3, 4, 5]
  sub_array = original_array[1..3]

This code will extract a sub-array from a larger array. The original array is declared on the first line with the values 1, 2, 3, 4 and 5. The sub_array is then declared on the second line, using the original array and the array slicing operator to extract values from 1 to 3. In this scenario, the sub_array will contain the values 2, 3 and 4. Array slicing is a powerful technique to extract values from a larger array, allowing us to reference a subset of the array to use a new array.

ruby