Skip to content

Commit 2ccd05b

Browse files
committed
Add Iterate With An Offset Index as a ruby til
1 parent 6c15261 commit 2ccd05b

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_831 TILs and counting..._
13+
_832 TILs and counting..._
1414

1515
---
1616

@@ -648,6 +648,7 @@ _831 TILs and counting..._
648648
- [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md)
649649
- [Identify Outdated Gems](ruby/identify-outdated-gems.md)
650650
- [If You Detect None](ruby/if-you-detect-none.md)
651+
- [Iterate With An Offset Index](ruby/iterate-with-an-offset-index.md)
651652
- [Ins And Outs Of Pry](ruby/ins-and-outs-of-pry.md)
652653
- [Invoking Rake Tasks Multiple Times](ruby/invoking-rake-tasks-multiple-times.md)
653654
- [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Iterate With An Offset Index
2+
3+
You can iterate over a collection of items with the
4+
[`#each`](https://devdocs.io/ruby~2.5/enumerator#method-i-each) method. If you
5+
want to know the index of each item as you go, you can use the
6+
[`#each_with_index`](https://devdocs.io/ruby~2.5/enumerable#method-i-each_with_index)
7+
variant.
8+
9+
```ruby
10+
> ["one", "two", "three"].each_with_index do |item, index|
11+
puts "#{item} - #{index}"
12+
end
13+
one - 0
14+
two - 1
15+
three - 2
16+
=> ["one", "two", "three"]
17+
```
18+
19+
The initial index will always be `0` when using `#each_with_index`.
20+
21+
What about if you want the index value to be offset by some number?
22+
23+
You can use the
24+
[`#with_index`](https://devdocs.io/ruby~2.5/enumerator#method-i-with_index)
25+
method on an _enumerator_. It optionally takes an `offset` argument.
26+
27+
```ruby
28+
> ["one", "two", "three"].each.with_index(1) do |item, index|
29+
puts "#{item} - #{index}"
30+
end
31+
one - 1
32+
two - 2
33+
three - 3
34+
=> ["one", "two", "three"]
35+
```

0 commit comments

Comments
 (0)