Created
October 31, 2013 18:24
-
-
Save AhmedNadar/7254497 to your computer and use it in GitHub Desktop.
Calculate the sum of all elements in an array
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
# Calculate the sum of all elements in an array | |
def sum(array) | |
array.inject{|sum, e| sum + e} | |
end | |
# or i can use shortcut | |
def sum(array) | |
array.inject(:+) | |
end | |
puts array = [12,45,56,34,7,3,89,4,2,44] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment