Main Content

Direct access to object variable (attributes) in Ruby

Archive - Originally posted on "The Horse's Mouth" - 2010-02-02 07:45:04 - Graham Ellis

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