Skip to content

Instantly share code, notes, and snippets.

@dallas
Created May 13, 2010 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dallas/399501 to your computer and use it in GitHub Desktop.
Save dallas/399501 to your computer and use it in GitHub Desktop.
creating sum functions as an exercise
// 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;
}
# 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