Yitzhak
Yitzhak

Reputation: 363

Receiving undefined method error when monkey patching

I'm getting the the error

`<main>': undefined method `my_uniq' for Array:Class (NoMethodError)

when running the following code

class Array
  def my_uniq(array)
    new_arr = []

    array.each do |i|
      if !new_arr.include?(i)
        new_arr << i
      end
    end

    return new_arr
  end
end

test = Array.my_uniq([1,2,3])

Any help fixing this would be much appreciated.

Upvotes: 0

Views: 601

Answers (1)

Stefan
Stefan

Reputation: 114138

If you want to write a class method, you have to define it with self i.e. def self.my_uniq:

class Array
  def self.my_uniq(array)
    array.each_with_object([]) do |element, new_arr|
      new_arr << element unless new_arr.include?(element)
    end
  end
end

For class methods, the class itself is the receiver:

Array.my_uniq([1, 1, 2, 3, 3, 1])
#=> [1, 2, 3]

If you want to write an instance method, you omit self and the argument:

class Array
  def my_uniq
    each_with_object([]) do |element, new_arr|
      new_arr << element unless new_arr.include?(element)
    end
  end
end

For instance methods, an instance of that class is the receiver:

[1, 1, 2, 3, 3, 1].my_uniq
#=> [1, 2, 3]

Upvotes: 1

Related Questions