Our weekend challenge came in two parts this week; the first task was to rewrite the Ruby “inject” method.
Ruby has numerous built in methods for use on strings, arrays and hashes for commonly used operations. For example, some that I have already used frequently are the include, each, map, next and select methods. They also have pretty intuitive names so your code can almost read like a sentence.
One of the methods I haven’t used yet is the inject method. Unlike most of the built in Ruby methods, I don’t think it is obvious what this one does (perhaps this is why it was chosen for our challenge).
The inject method operates on an array to successively perform an operation on each element, starting from either the first element of the array or a specified parameter.
[1, 2, 3, 4].inject(:+) => 10
The above is doing the following maths:
- 1 + 2 = 3
- 3 + 3 = 6
- 6 + 4 = 10
I chose to use a recursive method as that made more sense to me. I spent a good amount of time not getting very far when trying to pass a block as the argument. It sounded like it should be straightforward, but I just couldn’t see why it wasn’t working.
A fellow student helped me to see where I was going wrong — which prompted me to go back over my blocks, procs and lambdas notes from earlier in the week. It finally now works for all instances of the inject method (hurray!).
Aside from coding, it’s been getting pretty festive over here in the Oldcorn household, even Percy is getting his Christmas on.