Skip to content

Instantly share code, notes, and snippets.

@100lp
Created February 3, 2013 10:32
Show Gist options
  • Save 100lp/4701215 to your computer and use it in GitHub Desktop.
Save 100lp/4701215 to your computer and use it in GitHub Desktop.
ou are used to this by now. Write for me three methods - calculate, add and subtract. The tests should all pass. Take a look at the hint if you have trouble! And as a little extra hint: remember that you can use something.is_a?(Hash) or another_thing.is_a?(String) to check an object's type.
def add(*numbers)
numbers.inject(0) { |sum, number| sum + number }
end
def subtract(*numbers)
sum = numbers.shift
numbers.inject(sum) { |sum, number| sum - number }
end
def calculate(*arguments)
# if the last argument is a Hash, extract it
# otherwise create an empty Hash
options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
options[:add] = true if options.empty?
return add(*arguments) if options[:add]
return subtract(*arguments) if options[:subtract]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment