What exactly is Ruby self
Ruby is an object-oriented langauage, a very powerful one. A Ruby class is an object of class Class. And all method calls in Ruby invoke with a receiver, which is the current object. We can refer to the current object by using keyword self
, the same as this
in Java in term of meaning but a slightly different usages.
In case you don’t know how to define class methods in Ruby, there are several ways to do it. But the one I prefer is,
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. I highly recommended you to read the smart summary by Paul Barry. And then you should get the idea what the following code is trying to do 🙂
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 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
And you’d get the same output.
2 Comments
Jump to comment form | comment rss [?] | trackback uri [?]