Instance variable accessors in Ruby
Encapsulation is a vital characteristic for proper object oriented implementation. In order to accomplish meaningful tasks with a given class, instances variables may need to be exposed given certain design constraints. The exposure of these instances variables are done through "getters" and "setters" which are responsible for assigning or retrieving a value to/from a particular variable (respectively). If we use the Binary Node Class from my previous post an example, the member variables "contents", "left", and "right" have been exposed by overriding the "=" operator (getter) and self-named functions.
For defining access to instance variables, Ruby provides a nice short cut through the use of the "attr_accessor" directive.
The Binary Node Class can be re-written as follows (15 lines vs. 38 lines):
class BinaryNode attr_accessor :contents, :left, :right @contents = nil @left = nil @right = nil public def initialize(data, leftChild, rightChild) @contents = data @left = leftChild @right = rightChild end end
In fact, there are a few variations to access instance variables, which can be configured according to "read" and "write" privileges.
- attr_reader :variable - read only access to "variable"
- attr_writer :variable - write only access to "variable"
- attr_accessor :variable - read and write access to "variable"