How to test block

In the advanced debugging exercise, we have this method:

My questions:

  1. I was trying to test it with pry but I don’t know how to give a &block parameter?
    I tried the following:
    [26] pry(main)> [1, 2, 3].my_inject {|el| el * el}
    NoMethodError: undefined method *' for nil:NilClass from: (pry):26:inblock in pry
    [27] pry(main)> add_one = Proc.new { |i| i + 1}
    => #Proc:0x007f7f8a2990d0@:27(pry)
    [28] pry(main)> [1, 2, 3].my_inject(add_one)
    NoMethodError: undefined method call' for nil:NilClass Did you mean? caller from: lib/exercises.rb:123:inmy_inject’
    from: (pry):28:in __pry__' [29] pry(main)> [1, 2, 3].my_inject(&add_one) NoMethodError: undefined method+’ for nil:NilClass
    from: (pry):27:in `block in pry

  2. I don’t know how the spec works for this part. I thought we should always define block but it seems that’s not the case.

Spec:
it ‘makes the first element the accumulator if no default is given’ do
expect do |block|
[“el1”, “el2”, “el3”].my_inject(&block)
end.to yield_successive_args([“el1”, “el2”], [nil, “el3”])
end

Thank you.

Hi!

Your two questions are connected: The inject method works differently depending on whether there is an accumulator given. If there is, then inject will iterate over the array and, for each element of the array, it will reassign the accumulator to the result of calling the block with the accumulator and the element of the array. If there isn’t an accumulator given, then inject starts off assigning the first element of the array to the accumulator and then it iterates over the remaining elements of the accumulator and reassigns the accumulator to the result of calling the block with the accumulator and the element of the array.

This means that if you want to test your inject method and you want to give it an accumulator, you would write, say, [1, 2, 3].my_inject(5) {|el| el * el}, for an accumulator of 5. If you want to test it without giving it an accumulator, you would write [1, 2, 3].my_inject {|el| el * el}, just like you did. However, with your code, this will break, because for i = 0, the accumulator will be nil, and Ruby doesn’t like it if you try to multiply nil with some number.

Think about how you could change your method definition and let me know if you need any hints!

Thank you! It worked.