[RESOLVED] RSPEC3: Confused as to why this code doesn't work #my_uniq

class Array
  def my_uniq
    self.reduce([]) { |unique, el| unique << el unless unique.include?(el) }

Why does this code snippet not solve the #my_uniq problem?

1) Array#my_uniq returns the unique elements
     Failure/Error: expect(array.my_uniq).to eq([1, 2, 3, 4])
       undefined method `include?' for nil:NilClass
     # ./lib/00_array_extensions.rb:50:in `block in my_uniq'
     # ./lib/00_array_extensions.rb:50:in `each'
     # ./lib/00_array_extensions.rb:50:in `reduce'
     # ./lib/00_array_extensions.rb:50:in `my_uniq'
     # ./spec/00_array_extensions_spec.rb:49:in `block (3 levels) in <top (required)>'

Hi Jay,

On my first read-through of your code, it looks like unique is referring to the empty array that you’re using as an accumulator. Are you calling include? on the right object/array?

Yeah I figured it would build and build and realize when it had the element as it went along.

I did some digging, and I think that the reason this won’t work is because of how reduce is modifying the accumulator over time.
I ran through your code using byebug, which could be a really good habit to get into.
You’ll want to type require 'byebug' at the top of your ruby file and then type byebug on it’s own line immediately after you enter the my_uniq definition.

When you run the specs again, your code will pause at the byebug marker and you can step through it line by line by tying s You’ll want to type display self and display unique so that they auto update every time you step through your code.

When you step through the code, you’ll see that unique is first undefined, then [1], then [1,2] and then undefined again. I hope this technique helps. In the meantime, you can get the same results as you intend by using an each loop and a results array instead of reduce.

1 Like