Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Ruby Programming
Previous Page Home Next Page

Virtual Attributes

These attribute accessing methods do not have to be just simple wrappers around an object's instance variables. For example, you might want to access the duration in minutes and fractions of a minute, rather than in seconds as we've been doing.

class Song
  def durationInMinutes
    @duration/60.0   # force floating point
  def durationInMinutes=(value)
    @duration = (value*60).to_i
aSong ="Bicylops", "Fleck", 260)
aSong.durationInMinutes 4.333333333
aSong.durationInMinutes = 4.2
aSong.duration 252

Here we've used attribute methods to create a virtual instance variable. To the outside world, durationInMinutes seems to be an attribute like any other. Internally, though, there is no corresponding instance variable.

This is more than a curiosity. In his landmark book Object-Oriented Software Construction , Bertrand Meyer calls this the Uniform Access Principle. By hiding the difference between instance variables and calculated values, you are shielding the rest of the world from the implementation of your class. You're free to change how things work in the future without impacting the millions of lines of code that use your class. This is a big win.
Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire