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):

  1. class BinaryNode
  2. attr_accessor :contents, :left, :right
  3.  
  4. @contents = nil
  5. @left = nil
  6. @right = nil
  7.  
  8. public
  9. def initialize(data, leftChild, rightChild)
  10. @contents = data
  11. @left = leftChild
  12. @right = rightChild
  13. end
  14.  
  15. 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"

0 Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment



(c) 2012 sheel kapur / powered by WordPress