« Passing code to procedures and yield in Ruby | Main | Ruby collections and strings - some new examples »
February 02, 2010
Direct access to object variable (attributes) in Ruby
Rather than writing getters and setters, in many Object Oriented languages you can access the variables within an object directly. That can be dangerous for code flexibility for the future, as it means that you're removing the possibility of interspersing code. However, it can be very convenient.
In Java, you'll mark members you want publicly visible as public; in Ruby you specify attr_accessor (for read and write variables) and attr_reader for read only variables. There's an example [here].
If you try to access an object variable for which you have not set up an appropriate accessor in Ruby, an exception will be thrown (I've put that into the example too!)
Posted by gje at February 2, 2010 07:45 AM