Created
July 15, 2014 20:54
-
-
Save ryanswood/651479bb420c80ff4439 to your computer and use it in GitHub Desktop.
Reduce / Inject
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
| class Array | |
| def my_inject(*args) | |
| acc = args.length >= 1 ? args[0] : self.shift | |
| self.each {|el| acc = yield acc, el} | |
| acc | |
| end | |
| end | |
| def assert_equal(actual, expected) | |
| puts "You expected #{expected} and got #{actual}" unless actual == expected | |
| end | |
| assert_equal([1,2,3,4].my_inject(0) { |sum, el| sum + el }, 10) # w/ a initial | |
| assert_equal([1,2,3,4].my_inject { |sum, el| sum + el }, 10) # w/o a initial | |
| assert_equal([1,2,3,4].my_inject(0) { |sum, el| sum * el }, 0) # w/ a initial | |
| assert_equal([1,2,3,4].my_inject { |sum, el| sum * el }, 24) # w/o a initial |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment