Within the instance methods of a class, the pseudovariable self can be used as needed. This is only a reference to the current receiver, the object on which the instance method is invoked.
eg.
class Book
def self.title
true
end
def title
true
end
end
self
refers to the object depends on its context. self.title
in the above example will be invoked by the (current) object, Book
. While title
will be invoked by the object, Book.new
. Therefore, to determine the value of self
, you need to think around where the self resides.There are only 2 things that change what self points to: There are only 2 things that change what self points to:
- Explicit receiver of method call
puts self #self is "main", the top-level object instance
Object.new #self is temporarily changed to the class Object,
but then back to main - class/module definition
puts self #Again, self is "main"
class Foo
puts self #self is now Foo
end
#self is back to being main
So to define a method as a class method, prefix the method name with the self keyword. The scope of self varies depending on the context. Inside an instance method, self resolves to the receiver object. Outside an instance method, but inside a class definition, self resolves to the class.
Now consider this example:
class SelfStudy
attr_accessor :name
def self
@name
end
def self.name
@name
end
def self.name=(name)
@name = name
end
def self.default_name
self.name = "ClassName"
end
def default_name
self.name = "InstanceName"
end
end
Now playing with this class:
puts SelfStudy.name
#=> nil
puts SelfStudy.default_name
#=> ClassName
me = SelfStudy.new
puts me.name
#=> nil
puts me.default_name
#=> InstanceName
puts SelfStudy.name
#=> ClassName
puts SelfStudy.default_name
#=> ClassName
Please note the I just want to play up with
self
in the above example. So instead of defining @name
in self
method. As you should already know, you may simply replace it with@name
=
nil
No comments:
Post a Comment