-1

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
John
  • 443
  • 8
  • 19

1 Answers1

1
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.

yamafontes
  • 5,552
  • 1
  • 18
  • 18
  • Much thanks Kepani. Would you be able to give me a specific example(s) for how parameters passed in would induce the add or subtract methods? – John Oct 30 '13 at 19:29
  • Thanks again! One last question, is how would you call the 'calculate' method (and with what elements as parameters) to produce the example that you just provided. My apologies on so many questions, I am a novice and have been trying to get this to make sense in my head so I'm trying to figure out how everything would work from start to finish. – John Oct 30 '13 at 19:42
  • You would call it just like any other method. the key here is that it uses the splat operator `*` to let you switch between individual arguments and an array of arguments. – yamafontes Oct 30 '13 at 19:49
  • thanks for your continued patience! I'm still working this out and if you have time I was wondering if you could give me an example of how you would call the method with *numbers and *arguments? I think I'm struggling to understand in layman terms what you pass in when calling 'calculate' to get either add or subtract, as the purpose/usefulness of this exercise is somewhat lost on me.... Maybe I need to do some research on what the more conventional uses of the splat operator enable but that may or may not be relevant here. – John Oct 30 '13 at 23:49