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?
When declaring a method, the self of the declaration is the declaring class/module, so effectively you are defining a class method. For the client, this works similar to a static method in java. The client would call the method on the class instead of an instance: MyClass.method.
The keyword self in Ruby enables you to access to the current object — the object that is receiving the current message. The word self can be used in the definition of a class method to tell Ruby that the method is for the self, which is in this case the class.
the method self refers to the object it belongs to. Class definitions are objects too. If you use self inside class definition it refers to the object of class definition (to the class) if you call it inside class method it refers to the class again.
Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.
Contrary to other languages, Ruby has no class methods, but it has singleton methods attached to a particular object.
cat = String.new("cat") def cat.speak 'miaow' end cat.speak #=> "miaow" cat.singleton_methods #=> ["speak"]
def cat.speak
creates a singleton method attached to the object cat.
When you write class A
, it is equivalent to A = Class.new
:
A = Class.new def A.speak "I'm class A" end A.speak #=> "I'm class A" A.singleton_methods #=> ["speak"]
def A.speak
creates a singleton method attached to the object A. We call it a class method of class A.
When you write
class A def self.c_method 'in A#c_method' end end
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. Thus def self.c_method
is equivalent to def 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.
A.singleton_methods => ["c_method", "speak"]
(*) technically, in this case where A
has already been created by A = Class.new
, class A
reopens 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 means Class.new
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With