Skip to content

Instantly share code, notes, and snippets.

@kmazanec
Created August 16, 2013 19:51
Show Gist options
  • Save kmazanec/6252983 to your computer and use it in GitHub Desktop.
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.
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
@kmazanec
Copy link
Author

Good point! I tested it and reduce is a lot faster, too!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment