Last active
August 15, 2018 02:25
-
-
Save micahboyd/1f90084b403606b788bf5df24e6083ff to your computer and use it in GitHub Desktop.
Reduce vs each with_object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| range = (1..10) | |
| range.reduce([]) do |sum, x| | |
| (sum << x + 2) if x.even? # doesn't work! | |
| end | |
| range.reduce([]) do |sum, x| | |
| x.even? ? (sum << x + 2) : sum # works... | |
| end | |
| range.each.with_object([]) do |x, sum| | |
| (sum << x + 2) if x.even? # works better! | |
| end | |
| # The way reduce works is it sets the 'sum' variable based on the | |
| # return value of the last operation, including the initial value. | |
| # That means each iteration needs to return something so that it | |
| # can be passed along to the next operation. | |
| # Each with object on the other hand does not care about the return | |
| # value because it is not using it to set the 'sum' variable. Instead | |
| # 'sum' is set by the initial value and is then passed along in each | |
| # iteration and the final output. That lets you do operations that | |
| # don't return anything, as shown above, making your code more terse. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment