Skip to content

Commit 95dec79

Browse files
committed
Add Destructure The First Item From An Array as a Ruby til
1 parent 92ed23f commit 95dec79

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1153 TILs and counting..._
13+
_1154 TILs and counting..._
1414

1515
---
1616

@@ -895,6 +895,7 @@ _1153 TILs and counting..._
895895
- [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md)
896896
- [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md)
897897
- [Define A Method On A Struct](ruby/define-a-method-on-a-struct.md)
898+
- [Destructure The First Item From An Array](ruby/destructure-the-first-item-from-an-array.md)
898899
- [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md)
899900
- [Disassemble Some Codes](ruby/disassemble-some-codes.md)
900901
- [Double Splat To Merge Hashes](ruby/double-splat-to-merge-hashes.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Destructure The First Item From An Array
2+
3+
In true Ruby fashion, there are plenty of idomatic ways to get the first
4+
item from an array.
5+
6+
One of the ways is with assignment destructuring of the array.
7+
8+
It is common to see assignment destructuring with tuples:
9+
10+
```ruby
11+
> name, email = ['Liz', '[email protected]']
12+
=> ["Liz", "[email protected]"]
13+
> name
14+
=> "Liz"
15+
> email
16+
17+
```
18+
19+
If you only want the first element, try this:
20+
21+
```ruby
22+
> name, *rest = ['Liz', '[email protected]']
23+
=> ["Liz", "[email protected]"]
24+
> name
25+
=> "Liz"
26+
> rest
27+
28+
```
29+
30+
The first element is assigned to `name` and the remaining items in the array
31+
are assigned to `rest`. That's because of the `*`.
32+
33+
I like to use this approach with an array-returning method.
34+
35+
```ruby
36+
> def lookup_person(id)
37+
['Liz', '[email protected]', id]
38+
end
39+
=> :lookup_person
40+
> name, *rest = lookup_person(22)
41+
=> ["Liz", "[email protected]", 22]
42+
> name
43+
=> "Liz"
44+
irb(main):013:0> rest
45+
46+
```
47+
48+
This method works as expected when dealing with an empty array.
49+
50+
```ruby
51+
> name, *rest = []
52+
=> []
53+
> name
54+
=> nil
55+
> rest
56+
=> []
57+
```
58+
59+
In all of these, `, *rest` is important because otherwise the statement will be
60+
a standard variable assignment.

0 commit comments

Comments
 (0)