First
Video transcript & code
Just a quick tip today. It's one of those things that I often forget, and so I hope that by making an episode about it, I'll finally remember it.
Like many languages, in Ruby we can fetch the first item in an array by using subscript zero.
shopping_list = [:eggs, :olives, :cheese, :salsa] shopping_list[0] # => :eggs
Unlike a lot of those other languages, in Ruby there's an alternative to this syntax: the #first method.
shopping_list = [:eggs, :olives, :cheese, :salsa] shopping_list.first # => :eggs
In terms of character count, this is a longer expression. But it's so expressive that I invariably prefer the #first over square brackets when I know I need the first element.
What if we need the first two items in the array? For this I usually switch to square brackets.
shopping_list = [:eggs, :olives, :cheese, :salsa] shopping_list[0, 2] # => [:eggs, :olives]
But this isn't the only way to get the first two items. What I often forget is that #first
takes an optional argument: the number of elements to retrieve. Instead of the square brackets, we can use #first
with the argument 2 to get the first two elements.
shopping_list = [:eggs, :olives, :cheese, :salsa] shopping_list.first(2) # => [:eggs, :olives]
If there aren't enough elements in the array, #first
with an argument will return as many as it can.
shopping_list = [:eggs, :olives, :cheese, :salsa] shopping_list.first(5) # => [:eggs, :olives, :cheese, :salsa]
#first
with an argument differs in an important way from first without an argument. Without an argument, #first
may return nil
if the array is empty. By contrast, when given an argument it will always return an array, even if that array is empty. This is consistent with subscript notation.
[].first # => nil [].first(1) # => [] [][0,1] # => []
This example demonstrates, again, that the #first method takes a few more characters than subscripting. But there's just something about reading the word first
that helps me absorb the intent of code a few moments faster than I would given the equivalent subscript code. For that reason, I prefer to use #first
when I can.
And that's all for today. Happy hacking!
Responses