Ruby - Accessing the First and Last elements of the array

Introduction

Accessing the first and last elements of an array is easy with the first and last methods:

Demo

x = [1, 2, 3] 
puts x.first 
puts x.last

Result

If you pass a numeric parameter to first or last, you'll get that number of items from the start or the end of the array:

Demo

x = [1, 2, 3] 
puts x.first(2).join("-")

Result

Related Topic