1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Enumerate A Pairing Of Every Two Sequential Items as a ruby til

This commit is contained in:
jbranchaud
2020-12-11 09:26:12 -06:00
parent 1f9f102831
commit 304e09afcd
2 changed files with 34 additions and 1 deletions

View File

@@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
_972 TILs and counting..._
_973 TILs and counting..._
---
@@ -780,6 +780,7 @@ _972 TILs and counting..._
- [Edit Previous Parts Of The Pry Buffer History](ruby/edit-previous-parts-of-the-pry-buffer-history.md)
- [Editing Code In Pry](ruby/editing-code-in-pry.md)
- [Encode A String As URL-Safe Base64](ruby/encode-a-string-as-url-safe-base64.md)
- [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md)
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md)
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)

View File

@@ -0,0 +1,32 @@
# Enumerate A Pairing Of Every Two Sequential Items
From time to time, I've come across a situation where I want to iterate over a
list of items and have access to the item right after (or before depending on
how you want to think about it) the current item.
If I had a list like:
```ruby
items = [:a, :b, :c, :d, :z]
```
Then I'd love to turn it into a list of tuples like so:
```ruby
tuples = [[:a, :b], [:b, :c], [:c, :d], [:d, :z]]
```
I've finally come up with a one-liner I like for turning `items` into `tuples`.
```ruby
items.first(items.size - 1)
# => [:a, :b, :c, :d]
items.last(items.size - 1)
#=> [:b, :c, :d, :z]
items.first(items.size - 1).zip(items.last(items.size - 1))
#=> [[:a, :b], [:b, :c], [:c, :d], [:d, :z]]
```
I realized that if I take everything but the last item (using `first`) and take
everything but the first item (using `last`), then I can `zip` those two arrays
together into the list of tuples I was looking for.