Created
October 22, 2012 18:18
-
-
Save mikesjewett/3933129 to your computer and use it in GitHub Desktop.
Summing several numbers
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
# these all accomplish the same goal. | |
def sum(numbers=[]) | |
sum = 0 | |
numbers.each { |i| sum += i } | |
sum | |
end | |
def sum(numbers=[]) | |
numbers.inject(0) { |sum,element| sum += element } | |
end | |
# my favorite | |
def sum(numbers=[]) | |
numbers.inject(:+) | |
end | |
# this solution won't satisfy the spec for the exercise, but what if we didn't want to pass in an array? | |
# What if we wanted to allow a user to pass in an arbitrary set of numbers? Let's check out Ruby's SPLAT | |
def sum(*numbers) | |
numbers.inject(:+) | |
end | |
# using splat, we can call sum like this: | |
sum(1,2,3,4,5) | |
# or | |
sum(1,2,3) | |
# rather than passing in array like this: | |
sum([1,2,3,4]) | |
# I just wanted to introduce the splat, since I think it's pretty cool. More on this later. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment