Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Created March 11, 2014 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save arthurnn/9485781 to your computer and use it in GitHub Desktop.
Save arthurnn/9485781 to your computer and use it in GitHub Desktop.
def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc:
if klass.method_defined?(name) || klass.private_method_defined?(name)
if superklass.method_defined?(name) || superklass.private_method_defined?(name)
klass.instance_method(name).owner != superklass.instance_method(name).owner
else
true
end
else
false
end
end
class Foo
def hi; "hi"; end
end
class Bar < Foo
end
p method_defined_within?(:hi, Foo)
p method_defined_within?(:hi, Bar)
p method_defined_within?(:hi, Class.new(Bar))
module M
def say; "say what?"; end
end
class A
include M
end
class Beta < A
end
p method_defined_within?(:say, A)
p method_defined_within?(:say, A, M)
p method_defined_within?(:say, Beta)
p method_defined_within?(:say, Beta, M)
@gnomex
Copy link

gnomex commented Mar 11, 2014

$ ruby method_defined_whitin.rb 
true
false
false
true
false
false
false

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment