Can anyone explain to me what the meaning of adding self to the method definition is? Is it similar to the this keyword in java?
Can anyone explain to me what the meaning of adding self to the method
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Contrary to other languages, Ruby has no class methods, but it has singleton methods attached to a particular object.
def cat.speakcreates a singleton method attached to the object cat.When you write
class A, it is equivalent toA = Class.new:def A.speakcreates a singleton method attached to the object A. We call it a class method of class A.When you write
you create an instance of
Class(*). Inside the class definition, Ruby sets self to this new instance of Class, which has been assigned to the constant A. Thusdef self.c_methodis equivalent todef cat.speak, that is to say you define a singleton method attached to the object self, which is currently the class A.Now the class A has two singleton methods, that we commonly call class methods.
(*) technically, in this case where
Ahas already been created byA = Class.new,class Areopens the existing class. That’s why we have two singleton methods at the end. But in the usual case where it is the first definition of a class, it meansClass.new.