| 1. |
What is a getter method and how do you create it in Ruby? |
|
Answer» <P>A getter action is a method implementation that GETS the value of an instance variable of an object. With the getter method, you can retrieve the value of an instance variable outside the class. For example: //----start code-------- class Hi def initialize(name) @name = name end end obj1 = Hi.new('Bruno) p obj1.name #=> undefined method `name' for #<Hi:0x007fecd08cb288 @name="Bruno"> (NoMethodError) //----end code--------From the above example, the value of obj1.name cannot be retrieved outside Hi class. if you TRY to retrieve a value of an instance variable outside its class without a getter method, Ruby raises No Method Error. Defining a getter method within a class will MAKE the value of the name variable within the object. It is common practice to name a getter method as the instance variable’s name. //----start code--------- class Hi def initialize(name) @name = name end def name @name end end obj1 = Hi.new('Bruno’) p obj1.name #=> “Bruno” //----end code-------- |
|