diff --git a/README.md b/README.md index 1a8d4b4..4a5eb45 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_831 TILs and counting..._ +_832 TILs and counting..._ --- @@ -648,6 +648,7 @@ _831 TILs and counting..._ - [Get Info About Your RubyGems Environment](ruby/get-info-about-your-ruby-gems-environment.md) - [Identify Outdated Gems](ruby/identify-outdated-gems.md) - [If You Detect None](ruby/if-you-detect-none.md) +- [Iterate With An Offset Index](ruby/iterate-with-an-offset-index.md) - [Ins And Outs Of Pry](ruby/ins-and-outs-of-pry.md) - [Invoking Rake Tasks Multiple Times](ruby/invoking-rake-tasks-multiple-times.md) - [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md) diff --git a/ruby/iterate-with-an-offset-index.md b/ruby/iterate-with-an-offset-index.md new file mode 100644 index 0000000..1f2488e --- /dev/null +++ b/ruby/iterate-with-an-offset-index.md @@ -0,0 +1,35 @@ +# Iterate With An Offset Index + +You can iterate over a collection of items with the +[`#each`](https://devdocs.io/ruby~2.5/enumerator#method-i-each) method. If you +want to know the index of each item as you go, you can use the +[`#each_with_index`](https://devdocs.io/ruby~2.5/enumerable#method-i-each_with_index) +variant. + +```ruby +> ["one", "two", "three"].each_with_index do |item, index| + puts "#{item} - #{index}" + end +one - 0 +two - 1 +three - 2 +=> ["one", "two", "three"] +``` + +The initial index will always be `0` when using `#each_with_index`. + +What about if you want the index value to be offset by some number? + +You can use the +[`#with_index`](https://devdocs.io/ruby~2.5/enumerator#method-i-with_index) +method on an _enumerator_. It optionally takes an `offset` argument. + +```ruby +> ["one", "two", "three"].each.with_index(1) do |item, index| + puts "#{item} - #{index}" + end +one - 1 +two - 2 +three - 3 +=> ["one", "two", "three"] +```