Created
May 13, 2010 04:40
-
-
Save dallas/399501 to your computer and use it in GitHub Desktop.
creating sum functions as an exercise
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
// Sums all "number" arguments given. This includes floats by default. | |
// | |
// sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //=> 55 | |
// sum(1, "hey", 2, "3", 4, "five", 6, 'hi!', 7, 8.2, 9, 10); //=> 47.2 | |
function sum() { | |
var sum = 0; | |
for (i = 0; i < arguments.length; i++) { | |
var arg = arguments[i]; | |
if (typeof arg === 'number') sum += arg; | |
} | |
return sum; | |
} |
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
# Sums all Numeric arguments given. Could be made to sum only Integer arguments. | |
# (would exclude 8.2 in the second example). | |
# | |
# sum 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 #=> 55 | |
# sum 1, "hey", 2, "3", 4, "five", 6, 'hi!', 7, 8.2, 9, 10 #=> 47.2 | |
def sum(*args) | |
args.inject 0 do |sum, a| | |
sum += (a.is_a?(Numeric) ? a : 0) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment