InterviewSolution
| 1. |
What does ‘self’ mean? |
|
Answer» ‘self ‘ keyword in Ruby is used in different situations depending on the scenario. In other WORDS, 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: HelloClass 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-------- |
|