简体   繁体   中英

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.

If you want to write a class method , you have to define it with self ie 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM