Created
August 16, 2013 19:51
-
-
Save kmazanec/6252983 to your computer and use it in GitHub Desktop.
Recursively sum an indefinite number of elements. Use the splat operator to take any number of arguments. When calling this method, be sure to use the splat operator on any arrays that are passed to it or it will not function properly.
This file contains 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
def sum ( *args ) | |
args.length > 1 ? args.pop + sum(*args) : args.pop | |
end | |
test_array = [1,2,3,4] | |
puts sum(1,2) # ==> 3 | |
puts sum(*test_array) # ==> 10 | |
# be sure to use the *splat operator here so it gets passed (1,2,3,4) rather than ( [1,2,3,4] ) | |
puts sum(test_array[-1], test_array[-2]) # ==> 7 | |
# sum the last two elements of an array | |
# no need to use *splat because you are just accessing individual values in the array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good point! I tested it and
reduce
is a lot faster, too!