Thursday, October 13, 2011

Getters and setters in Ruby class

Now consider this fragment, and pay attention to the getmyvar, setmyvar, and myvar= methods:

class MyClass

NAME = "Class Name" # class constant
@@count = 0 # Initialize a class variable
def initialize # called when object is allocated
@@count += 1
@myvar = 10
end

def MyClass.getcount # class method
@@count # class variable
end

def getcount # instance returns class variable!
@@count # class variable
end

def getmyvar # instance method
@myvar # instance variable
end

def setmyvar(val) # instance method sets @myvar
@myvar = val
end
def myvar=(val) # Another way to set @myvar
@myvar = val
end
end

Now lets create instance of this class:
foo = MyClass.new # @myvar is 10
foo.setmyvar 20 # @myvar is 20
foo.myvar = 30 # @myvar is 30

Here we see that getmyvar returns the value of @myvar, and setmyvar sets it. (In the terminology of many programmers, these would be referred to as a getter and a setter.) These work fine, but they do not exemplify the Ruby way of doing things. The method myvar= looks like assignment overloading (though strictly speaking, it isn't); it is a better replacement for setmyvar, but there is a better way yet.

The class called Module contains methods called attr, attr_accessor, attr_reader, and attr_writer. These can be used (with symbols as parameters) to automatically handle controlled access to the instance data. For example, the three methods getmyvar, setmyvar, and myvar= can be replaced by a single line in the class definition:

attr_accessor :myvar

This creates a method myvar that returns the value of @myvar and a method myvar= that enables the setting of the same variable. Methods attr_reader and attr_writer create read-only and write-only versions of an attribute, respectively.

No comments:

Post a Comment