The receiver is A in A.medhod (B). It may appear that there is no receiver in front of the method. For example, in the following cases.
class ClassA
def say
puts instance_of? String #false
puts instance_of? ClassA #true
end
end
ClassA.new.say
#false
#true
instance_of? [Ruby] Difference between is_a? And instance_of? As I wrote in the explanation of
A.instance_of? B
At one point, A is an instance of B, but in the above example, ʻA.` is missing, isn't it?
In conclusion, the instance_of? Above is preceded by an instance of Class A. When referencing a method of the same class, inheritance class or included module, it is not necessary to precede the method with an instance (I think it is automatically attached). Addendum: I received a comment that "there is a rule that self is the receiver for method calls that do not explicitly write the receiver", but I think this way of thinking is easier to understand.
For example, in the following cases,
class ClassB
def say_b
say_b2
end
def say_b2
puts "bbb"
end
end
ClassB.new.say_b
# bbb
This doesn't feel strange, right? Methods of the same class can be executed from other methods without writing (or even writing) a receiver. Similarly, the instance_of? Method above is actually a method of the Object class of the superclass (strictly speaking, it seems to be a method of the Kernel module included in the Object class).
ClassA.new.method(:instance_of?).owner
=> Kernel
Perhaps the reason I felt uncomfortable when the first instance_of? Suddenly appeared was because I couldn't see the relationship between the instance_of? Method and Class A.
You can also check the receiver.
method(:Method).receiver
You can output with.
class ClassB
def say_b
say_b2
puts method(:say_b2).receiver
end
def say_b2
puts "bbb"
end
end
ClassB.new.say_b
# bbb
# #<ClassB:0x00007ff34d8a0550>
You can see that the receiver of say_b2 is an instance of ClassB. Actually, there is already an instance of ClassB before method (: say_b2).
Recommended Posts