Ruby program to implement getter and setter methods

bookmark

class Sample
    #constructor
    def initialize(val)
        @ins_var = val;
    end
    
    #Getter method
    def GetVal
        @ins_var;
    end
    
    def SetVal=(val)
        @ins_var = val;
    end
  
end

obj = Sample.new("Hello");

val = obj.GetVal();
print "Value is: ",val,"\n";

obj.SetVal = "Hiii";
val = obj.GetVal();
print "Value is: ",val,"\n";

 


Output:

Value is: Hello
Value is: Hiii