Reputation: 659
See this class definition:
class T
def respond_to?(name)
name.to_s == 't' || super
end
def t; p 't'; end
def t2; p 't2'; end
end
When I call
T.new.respond_to? :t2
It seems that it would return false, because either it equals to 't', nor does it respond to T's super class, which is Object. However, it returns true. So can anybody explain how this works?
Update: I realize what I thought before was wrong.
class P
def t; self.class; end
end
class C < P
def t
p self.class
p super
end
end
When I call C.new.t
I'd expect the result to be:
C
P
However, I got:
C
C
So return to the respond_to? issue, when I call super, it runs Object#respond_to?, but still in the context/scope of C, so it returns true.
Upvotes: 1
Views: 146
Reputation: 84114
super doesn't mean "forget you're an instance of T", it means call your superclass' implementation of respond_to?
That implementation isn't hard coded to check Object's method, it's a general implementation that goes over the object's ancestors checking for the existance of the method.
Upvotes: 1
Reputation: 160843
The super
does not mean check whether it respond to T
's super class, but just mean using the respond_to
method extended from the T
's super class.
Because T
has the instance method t2
, so it will return true
.
Upvotes: 2