1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Skip The Front Of An Array With Drop as a Ruby TIL

This commit is contained in:
jbranchaud
2024-09-25 22:43:04 -05:00
parent 2922bbdd6a
commit c33be14ec2
2 changed files with 46 additions and 1 deletions

View File

@@ -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).
_1443 TILs and counting..._
_1444 TILs and counting..._
---
@@ -1224,6 +1224,7 @@ _1443 TILs and counting..._
- [Silence The Output Of A Ruby Statement In Pry](ruby/silence-the-output-of-a-ruby-statement-in-pry.md)
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
- [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md)
- [Skip The Front Of An Array With Drop](ruby/skip-the-front-of-an-array-with-drop.md)
- [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md)
- [Specify How Random Array#sample Is](ruby/specify-how-random-array-sample-is.md)
- [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md)

View File

@@ -0,0 +1,44 @@
# Skip The Front Of An Array With Drop
I've long been familiar with Ruby's
[`Array#take`](https://apidock.com/ruby/Array/take) which is a handy way to
grab the first few elements of an array.
```ruby
> [:a, :b, :c, :d, :e, :f, :g].take(4)
=> [:a, :b, :c, :d]
```
But what if I want to skip those first four elements of the array and get what
remains. That is where [`Array#drop`](https://apidock.com/ruby/Array/drop)
comes in.
```ruby
> [:a, :b, :c, :d, :e, :f, :g].drop(4)
=> [:e, :f, :g]
```
How about a couple practical situations for use in a Rails app.
Here I want to segment out the first 6 books and whatever remains:
```
def index
@books = Book.order(created_at: :desc).limit(10)
@featured_books = @books.take(6)
@remaining_books = @books.drop(6)
end
```
Or, what about cleaning up all but the first of these duplicate records:
```
Book
.where(title: "The Murder of Roger Ackroyd")
.drop(1)
.each { |duplicate_book| duplicate_book.destroy }
```
The first record is ignored (dropped from the array) and the following records
are processed by the `#each` where they get destroyed.