Ask your own question, for FREE!
Computer Science 83 Online
OpenStudy (anonymous):

Any pro Ruby users out there? I know these functions are for adding and subtracting numbers. 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 but I'd love to know some things. In the first function, how does the inject method work? Why does it need a 0 parameter? and what is going on in the curly braces? In the 2nd function why do we 'sum = numbers.shift' ? What is the shift method? and again, what is going on with the inject and between th

OpenStudy (anonymous):

The 0 is the initial number in the sum. You can think of the execution of (add(1,2,3,4,5) as ((((0 + 1) + 2) + 3) + 4) + 5. But the inject function needs an initial argument, that's just the way it was designed. Shift removes the first element of an array and returns it. Keep in mind that the arguments are being collected and placed in an array (that's what the * in the argument list does, puts all the arguments in an array called 'numbers'). So say we have subtract(3,2,1). Order matters with subtraction, so we take the first value in numbers 3 and then give it to inject. So ultimately it ends up doing ((3 - 2) - 1). As for the curly braces, that's a "block", or a piece of code that can be called later. The inject function calls the block for every element in the array.

OpenStudy (anonymous):

Thank you! Big help! So if I wrote inject(2), It would start from ((((((2+1) + 2) + 3) + 4) +5). So the 'Sum' in { |sum, number| sum + number } is that just another Ruby function, or is it being declared as a variable? Ahhh that's good to know about the 'shift' function, very interesting!

OpenStudy (anonymous):

Sum is the variable containing the current sum! So when you start out, it's 0, and then say, if you have 1 + 2 + 3, and you've already done (1 + 2), then the block gets sum as 3 (1 + 2) and number as 3 (the current number from the arguments)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Latest Questions
Midnight97: Can I get some help because I forgot how to do this
13 minutes ago 5 Replies 2 Medals
YouMyPlug: A lil sum sum
15 minutes ago 20 Replies 5 Medals
SnowKitty: Can I get some help please
3 hours ago 7 Replies 2 Medals
Coyote: Trigonometry
3 hours ago 3 Replies 2 Medals
Thayes: Listen
5 hours ago 5 Replies 1 Medal
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!