Search code examples
arraysrubymonkeypatching

Monkey Patching Arrays in Ruby


I added my own method to the Array class that does the same thing as Array#uniq.

This is my version:

arr = ["fun", "sun", 3, 5, 5, 5, 1, 2, 1, "fun"]

class Array
    def my_uniq
        new_arr = []
        each do |item|
            new_arr << item unless new_arr.include?(item)
        end
        new_arr
    end
end

print arr.my_uniq

Is there a way to modify this to return the indices of the unique elements rather than the elements themselves?


Solution

  • each_with_index will allow you to iterate your array and return indexes.

    each_with_index do |item, index|
      newArr << index unless newArr.include?(item)
    end