Know Your-self

Getting to know your-self can be a lifelong process. To help you along the way — here are a few things I’ve learned about the self keyword in ruby.

In Ruby, the keyword self should be used in the following ways.

  1. To set or get instance attributes inside a class method.
  2. To define a class method.
  3. To reference the calling object within an instance method definition.

Consider the below code which demonstrates both the first and third uses of self as mentioned above.

class Person   
    attr_accessor :name    
    def initialize(name)     
@name=name
end
    def introduce
"Hi, I'm #{self.name}"
end
end

The introduce method above uses string interpolation to insert the name attribute of the object being called. Since the introduce method is called by a Person object, self references that specific instance and the introduce method gets the name attribute.

jason = Person.new("Jason")
=> #<Person:0x007fd0bb8244f0 @name="Jason">
alison = Person.new("Alison")
=> #<Person:0x007fd0bc01fe70 @name="Alison">
jason.introduce
=> "Hi, I'm Jason"
alison.introduce
=> "Hi, I'm Alison"

Let’s build on to our above code to demonstrate the second use of self as noted above.

class Person
    attr_accessor :name
    @@people = []
    def initialize(name)     
@name=name
@@people << self
end
    def introduce
"Hi, I'm #{self.name}"
end
    def what_am_i
self
end
    def self.everyone
@@people
end
end

Let’s look at how self works when we call the methods we added.

jason = Person.new("Jason")
=> #<Person:0x007fd0bb8244f0 @name="Jason">
alison = Person.new("Alison")
=> #<Person:0x007fd0bc01fe70 @name="Alison">
jason.introduce
=> "Hi, I'm Jason"
alison.introduce
=> "Hi, I'm Alison"
jason.what_am_i
=> #<Person:0x007fd0bb8244f0 @name="Jason">
alison.what_am_i
=> #<Person:0x007fd0bc01fe70 @name="Alison">
Person.everyone
=> [#<Person:0x007fd0bb8244f0 @name="Jason">, #<Person:0x007fd0bc01fe70 @name="Alison">]

The what_am_i method returns self, which points to whichever instance of the class the what_am_i method is being called on. Thus, the what_am_i method returns a Person object.

Our self.everyone method, is a class method. Instance methods (like introduce) are methods that can only be operated by an instance of a class, whereas class methods can only be operated by the class object itself. This allows us to return the class variable @@people which contains all person object instances that have been created (in the above code, alison and jason). The self.everyone method would not work if it was created as an instance method.