This is a follow-up question to How to determine the class a method was defined in? (hope you don't mind the similarity)
Given a class hierarchy, can a method retrieve its own Method
instance?
class A
def foo
puts "A#foo: `I am #{method(__method__)}'"
end
end
class B < A
def foo
puts "B#foo: `I am #{method(__method__)}'"
super
end
end
A.new.foo
# A#foo: `I am #<Method: A#foo>'
B.new.foo
# B#foo: `I am #<Method: B#foo>'
# A#foo: `I am #<Method: B#foo>' # <- A#foo retrieves B#foo
So that B.new.foo
instead prints
# B#foo: `I am #<Method: B#foo>'
# A#foo: `I am #<Method: A#foo>' # <- this is what I want
In the previous question, Jörg W Mittag suspected that retrieving the class a method was defined in might violate object-oriented paradigms. Does this apply here, too?
Shouldn't a method "know itself"?
Aucun commentaire:
Enregistrer un commentaire