mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Map With Index Over An Array as a ruby til
This commit is contained in:
@@ -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/).
|
||||
|
||||
_850 TILs and counting..._
|
||||
_851 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -669,6 +669,7 @@ _850 TILs and counting..._
|
||||
- [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md)
|
||||
- [Limit Split](ruby/limit-split.md)
|
||||
- [Listing Local Variables](ruby/listing-local-variables.md)
|
||||
- [Map With Index Over An Array](ruby/map-with-index-over-an-array.md)
|
||||
- [Mock Method Chain Calls With RSpec](ruby/mock-method-chain-calls-with-rspec.md)
|
||||
- [Mocking Requests With Partial URIs Using Regex](ruby/mocking-requests-with-partial-uris-using-regex.md)
|
||||
- [Navigate Back In The Browser With Capybara](ruby/navigate-back-in-the-browser-with-capybara.md)
|
||||
|
||||
29
ruby/map-with-index-over-an-array.md
Normal file
29
ruby/map-with-index-over-an-array.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Map With Index Over An Array
|
||||
|
||||
The [`#map`](https://devdocs.io/ruby~2.5/enumerable#method-i-map) method on its
|
||||
own allows you to interact with each item of an array, producing a new array.
|
||||
|
||||
```ruby
|
||||
[1,2,3].map { |item| item * item }
|
||||
#=> [1,4,9]
|
||||
```
|
||||
|
||||
If you also want access to the index of the item, you'll need some help from
|
||||
other enumerable methods. As of Ruby 1.9.3, you can chain on
|
||||
[`#with_index`](https://devdocs.io/ruby~2.5/enumerator#method-i-with_index):
|
||||
|
||||
```ruby
|
||||
[1,2,3].map.with_index { |item, index| item * index }
|
||||
#=> [0,2,6]
|
||||
```
|
||||
|
||||
This method has the added benefit of allowing you to specify the starting value
|
||||
of the index. It normally starts with `0`, but you could just as easily start
|
||||
at `1`:
|
||||
|
||||
```ruby
|
||||
[1,2,3].map.with_index(1) { |item, index| item * index }
|
||||
#=> [1,4,9]
|
||||
```
|
||||
|
||||
[source](https://stackoverflow.com/a/11280903/535590)
|
||||
Reference in New Issue
Block a user