From 95dec7933b583c31748bec5660564a8d1871892a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 23 Sep 2021 13:03:25 -0500 Subject: [PATCH] Add Destructure The First Item From An Array as a Ruby til --- README.md | 3 +- ...estructure-the-first-item-from-an-array.md | 60 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 ruby/destructure-the-first-item-from-an-array.md diff --git a/README.md b/README.md index dde44b1..9e4bc1e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1153 TILs and counting..._ +_1154 TILs and counting..._ --- @@ -895,6 +895,7 @@ _1153 TILs and counting..._ - [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md) - [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md) - [Define A Method On A Struct](ruby/define-a-method-on-a-struct.md) +- [Destructure The First Item From An Array](ruby/destructure-the-first-item-from-an-array.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) - [Disassemble Some Codes](ruby/disassemble-some-codes.md) - [Double Splat To Merge Hashes](ruby/double-splat-to-merge-hashes.md) diff --git a/ruby/destructure-the-first-item-from-an-array.md b/ruby/destructure-the-first-item-from-an-array.md new file mode 100644 index 0000000..e8d0ae5 --- /dev/null +++ b/ruby/destructure-the-first-item-from-an-array.md @@ -0,0 +1,60 @@ +# Destructure The First Item From An Array + +In true Ruby fashion, there are plenty of idomatic ways to get the first +item from an array. + +One of the ways is with assignment destructuring of the array. + +It is common to see assignment destructuring with tuples: + +```ruby +> name, email = ['Liz', 'liz.lemon@nbc.com'] +=> ["Liz", "liz.lemon@nbc.com"] +> name +=> "Liz" +> email +=> "liz.lemon@nbc.com" +``` + +If you only want the first element, try this: + +```ruby +> name, *rest = ['Liz', 'liz.lemon@nbc.com'] +=> ["Liz", "liz.lemon@nbc.com"] +> name +=> "Liz" +> rest +=> ["liz.lemon@nbc.com"] +``` + +The first element is assigned to `name` and the remaining items in the array +are assigned to `rest`. That's because of the `*`. + +I like to use this approach with an array-returning method. + +```ruby +> def lookup_person(id) + ['Liz', 'liz.lemon@nbc.com', id] + end +=> :lookup_person +> name, *rest = lookup_person(22) +=> ["Liz", "liz.lemon@nbc.com", 22] +> name +=> "Liz" +irb(main):013:0> rest +=> ["liz.lemon@nbc.com", 22] +``` + +This method works as expected when dealing with an empty array. + +```ruby +> name, *rest = [] +=> [] +> name +=> nil +> rest +=> [] +``` + +In all of these, `, *rest` is important because otherwise the statement will be +a standard variable assignment.