Sunday, November 17, 2013

Methods calculate, add, subtract

CODE:
def calculate(*args)
  if args[-1].is_a?(Hash)
    if args[-1][:add]
      add(*args[0..-2])
    elsif args[-1][:subtract]
      subtract(*args[0..-2])
    end
  else
    add(*args)
  end
end

def add(*numbers)
  numbers.inject(0) { |sum, num| sum + num }
end

def subtract(*numbers)
  numbers.inject { |dif, num| dif - num }
end

TESTS from rubymonk
invoking add(4, 5) returns 9 ✔
invoking add(-10, 2, 3) returns -5 ✔
invoking add(0, 0, 0, 0) returns 0 ✔
invoking subtract(4, 5) returns -1 ✔
invoking subtract(-10, 2, 3) returns -15 ✔
invoking subtract(0, 0, 0, 0, -10) returns 10 ✔
defaults to addtion when no option is specified ✔
invoking calculate(4, 5, add: true) returns 9 ✔
invoking calculate(-10, 2, 3, add: true) returns -5 ✔
invoking calculate(0, 0, 0, 0, add: true) returns 0 ✔
invoking calculate(4, 5, subtract: true) returns -1 ✔
invoking calculate(-10, 2, 3, subtract: true) returns -15 ✔
invoking calculate(0, 0, 0, 0, -10, subtract: true) returns 10 ✔

No comments:

Post a Comment