First and Last
Getting the first or last elements of an array is a common operation in programming. While
getting the first element is straightforward in most languages (using index 0), retrieving the last element often requires additional steps. Ruby provides the obvious API to this with its first and last methods.
array = [10, 20, 30, 40, 50]
first_element = array.first # => 10
last_element = array.last # => 50
const array = [10, 20, 30, 40, 50];
const firstElement = array[0]; // => 10
const lastElement = array[array.length - 1]; // => 50
Beautiful! But maybe you feel that human language elegance is superfluous and first is already expressed more concisely as [0]. Fair enough. But perhaps I can entice you with another trick these methods have up their sleeves.
array = [10, 20, 30, 40, 50]
first_two = array.first(2) # => [10, 20]
last_three = array.last(3) # => [30, 40, 50]
const array = [10, 20, 30, 40, 50];
const firstTwo = array.slice(0, 2); // => [10, 20]
const lastThree = array.slice(-3); // => [30, 40, 50]
Let's take a moment and appreciate how when we're reading this code it directly parses in our brain as "first two" and "last three". Intuitive and expressive!
History
I wasn't able to figure out when these methods were introduced in Ruby, but the ability to pass an argument to return more than one element was added in Ruby 1.8, released in 2003, as mentioned in the Japanese release notes.
Other languages predating Ruby with APIs for first and last include Smalltalk and Lisp, with Smalltalk being a known source of inspiration to Ruby in general.
Since Ruby's implementation, outside of functional programming languages, languages like Rust and Swift have also adopted similar first and last methods for their collections.
Second, Third and... 🫣
ActiveSupport, the utility library that is part of Ruby on Rails, adds second, third, fourth and fifth methods to Array as well. Originally methods all the way up to tenth were added, but after some controversy they were reduced to just five, along with forty_two to remind us of the ultimate answer to the meaning of life. A sweet reminder that Ruby is a human-centric language rather than a computer-centric one!
ActiveSupport also adds first and last methods to String. Can you guess what they return?