RSPEC 2 my_inject error: expected given block to yield successively with arguments, but yielded with unexpected arguments

def my_inject(&blk)

acc = self.first

 i = 1
  while i < self.length
    blk.call(acc, self[i])
    acc = blk.call(acc, self[i])
    i += 1
  end
acc

end

end

error: Failures:

  1. Array#my_inject calls the block passed to it
    Failure/Error:
    expect do |block|
    [1, 2].my_inject(&block)
    end.to yield_control.once

    expected given block to yield control once but yielded twice

    ./spec/03_iteration_spec.rb:182:in `block (3 levels) in <top (required)>’

  2. Array#my_inject makes the first element the accumulator if no default is given
    Failure/Error:
    expect do |block|
    [“el1”, “el2”, “el3”].my_inject(&block)
    end.to yield_successive_args([“el1”, “el2”], [nil, “el3”])

    expected given block to yield successively with arguments, but yielded with unexpected arguments
    expected: [[“el1”, “el2”], [nil, “el3”]]
    got: [[“el1”, “el2”], [“el1”, “el2”], [nil, “el3”], [nil, “el3”]]

    ./spec/03_iteration_spec.rb:188:in `block (3 levels) in <top (required)>’

  3. Array#my_inject yields the accumulator and each element to the block
    Failure/Error:
    expect do |block|
    [1, 2, 3].my_inject(&block)
    end.to yield_successive_args([1, 2], [nil, 3])

    expected given block to yield successively with arguments, but yielded with unexpected arguments
    expected: [[1, 2], [nil, 3]]
    got: [[1, 2], [1, 2], [nil, 3], [nil, 3]]

    ./spec/03_iteration_spec.rb:194:in `block (3 levels) in <top (required)>’

Finished in 0.07263 seconds (files took 0.23005 seconds to load)

I’m sorry, you’re going to need to give me more than just your code and what the console outputs when you run RSpec. Can you tell me what you’ve tried, where you’re stuck on, what you’re confused about, etc.?

Hi,

I bet your code works if you try to run sample tests, but the specs are failing. I see that could be confusing!

The reason your specs are failing is because you’re calling prc.call too many times. See how you invoke it twice within your while loop, once before you set the accumulator equal to the result? That means your’e calling the block twice for each element inside of your while loop, which is producing twice as many yields as you need and confusing the rspec suite.

Hopefully this helps! Let us know if you have any further questions.

best,
Shalin
Hacker in Residence, NYC

1 Like

you’re absolutely right!
I just removed the first proc.call and now it works without failing any of the specs.
Thank you!

1 Like