I've been coding in Ruby for sometime now, but I don't understand when to use:
def self.METHOD_NAME end
or just:
def METHOD_NAME end
In any Rails model. Is "self" a modifier like private in Java? When should I use it and when not?. Thanks a ton.
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup.
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.
def self.method_name end
defines a class method.
def method_name end
defines an instance method.
This is a pretty good post on it.
A quick explanation of what that means:
In ruby, you can define methods on a particular object:
a = "hello" def a.informal "hi" end a.informal => "hi"
What happens when you do that is that the object a, which is of class String
, gets its class changed to a "ghost" class, aka metaclass, singleton class or eigenclass. That new class superclass is String
.
Also, inside class definitions, self
is set to the class being defined, so
class Greeting def self.say_hello "Hello" end #is the same as: def Greeting.informal "hi" end end
What happens there is that the object Greeting
, which is of class Class
, gets a new metaclass with the new methods, so when you call
Greeting.informal => "hi"
There's no such thing as class methods in ruby, but the semantics are similar.
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