1.

What does ‘self’ mean?

Answer»

‘self ‘ keyword in Ruby is used in different situations depending on the scenario. In other WORDS,
One context of a call to ‘self’ keyword refers to the parent class. Whereas in a different context, ‘self’ keyword may refer to a PARTICULAR instance of a class.

Class definition self

we can refer to ‘self’ keyword when defining a class in Ruby. We have a Hello class, inside which we’re outputting the VALUE of self:

For example:

//----start CODE-------- class Hello    puts "Self is: #{self}" end //----end code--------

When calling ‘self’ directly inside the context of a class definition, the self is equivalent to the parent class in which it was defined; Hello, in the above case.

Output is

Self is: Hello  

Class method self

A class method is a method that refers only to that class in all contexts. You can define the class method with ‘Self’ keyword. The following example DEMONSTRATES how you can define a class method.

//----start code-------- class Hello  # Define class variable  name = "John Doe"  # Getter method  def self.name    puts "Self inside class method is: #{self}"    return name  end end puts "Hello class method 'name' is: #{Hello.name}" //----end code--------

As explained earlier ‘self’ inside a class method definition refers to that parent class object — Hello in this case. We also call Hello.name in the output, to show that our class method getter behaves as expected:

//----start code-------- Self inside a class method is: Hello Hello class method 'name' is: John Doe   //----end code--------


Discussion

No Comment Found