so I'm working through some examples of Ruby Methods from the rubymonk website and am having trouble interpreting what is going on in the code below. More specifically, I was hoping that someone might be able to help explain in layman's terms what each line in the code from the 'calculate' method is describing? I really appreciate any and all help!
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)
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
options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
Create a new hash called options
. This will either be assigned to the last element in the arguments array, or an empty one if that is not a hash. In ruby, like python, using -1 as an array index gets you the last element in an array.
options[:add] = true if options.empty?
Set the value in the hash that matches the key :add
to true if the hash you just created is empty.
return add(*arguments) if options[:add]
return subtract(*arguments) if options[:subtract]
return the result of add
or subtract
with the same parameters you passed to this function, based on the state of the options
hash you just created.
For example:
arguments = [{}, {:add => false, :subtract => true}]
would induce the subtract method if used as your parameter.