Ruby allows to define class and instance variables. Ruby doesn’t allow 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 about this in 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 are used to access the variable’s data. The Syntax to define getter methods is simple. Define the method name as 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;
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 getter method; except prefix the argument with equal (“=”) sign to allow to pass the value to the variable of the class. Here is an example to define a setter method;
@in_var = val
Complete working example of getter and setter methods is here.
@@class_variable = "Hi!"
@instance_variable = 100
@instance_variable = 10
@instance_variable = value
@@class_variable = value
puts "Current value(s):"
obj = Sample.new
puts "New value(s):"
puts Sample.class_variable = 100
puts obj.instance_variable = "Hello!"
| Nick |