Ruby allows defining class and instance variables. Ruby doesn’t allow us to access the variables of the class directly; instead, we can use methods to access or modify the variables of the class.
We have discussed an overview of classes in Ruby through my previous Article “Ruby Programming – An Overview on Classes“.
Through this article, we will discuss how to access variables of the class in Ruby.
There are different ways we can access variables of the class in Ruby. One way is defining the methods of the class; we already discussed this in the above Article. We will discuss the other way to access the variables of the class in Ruby through this Article.
Using Getter and Setter methods
Ruby provides getter and setter methods to ease to access the variables of the class. Getter methods are used to get the data from the variables of the classes and whereas setter methods are used to set the data of the variables of the classes. These methods can be used for both instance and class variables.
Getter methods
Getter methods are used to access the variable’s data. The Syntax to define getter methods is simple. Define the method name as the variable name and return the variable’s data. Here is a simple example to define a getter method. Observe that, NO need to use the return statement to return the data of the variable; instead required to mention the variable name;
def in_var @in_var end
Setter methods
Setter methods are used to set the variable’s data. Hence you need to pass the value through this method to set the variables data. The Syntax is simple like the getter method; except prefix of the argument with an equal (“=”) sign to allow to pass the value to the variable of the class. Here is an example to define a setter method;
def in_var=(val) @in_var = val end
A complete working example of getter and setter methods is here.
class Sample @instance_variable @@class_variable = "Hi!" def initialize @instance_variable = 100 end def instance_variable @instance_variable = 10 end def instance_variable=(value) @instance_variable = value end def Sample.class_variable @@class_variable end def Sample.class_variable=(value) @@class_variable = value end end puts "Current value(s):" puts Sample.class_variable obj = Sample.new puts obj.instance_variable puts "New value(s):" puts Sample.class_variable = 100 puts obj.instance_variable = "Hello!"
| Nick |