LoginSignup
4
2

More than 5 years have passed since last update.

undef_methodとremove_methodの違い

Last updated at Posted at 2018-02-25

undef_methodとremove_methodの違いは継承元のメソッドが代わりに呼ばれるかどうか

remove_methodは現在のクラスからメソッドを削除しますが、
継承元にメソッドが定義されてあれば継承元のメソッドが呼ばれます。

undef_methodはメソッド呼び出しへのレスポンスを止めます。
remove_methodと違い、継承元のクラスにメソッドが定義されていてもエラーとなります。


class A
  def my_method
    p "This is A's my_method"
  end
end

class RemovedB < A
  def my_method
    p "This is B's my_method"
  end
  remove_method :my_method
end

class UndefedB < A
  def my_method
    p "This is B's my_method"
  end
  undef_method :my_method
end
RemovedB.new.my_method
=> "This is A's my_method"

remove_method では継承元Aのメソッドが呼ばれる。

RemovedB.new.my_method 
=> undefined method `my_method' for #<UndefedB:0x007fe382956088> (NoMethodError)

undef_methodではメソッドが呼ばれない。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2