Created
April 29, 2016 15:00
-
-
Save joshuastr/7743f81393deb761a8e31eb651336bc4 to your computer and use it in GitHub Desktop.
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
| sum = 0 | |
| arr.each do |x| | |
| if yield(x) | |
| sum += x | |
| end | |
| end | |
| sum | |
| end | |
| # now we can sum_if with various blocks, ex: | |
| # sum if even: | |
| a = sum_if([1,2,3,4,5]) do |i| | |
| i % 2 == 0 | |
| end | |
| puts a | |
| # sum if > 3 | |
| b = sum_if([1,2,3,4,5]) do |i| | |
| i > 3 | |
| end | |
| puts b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment