February 2, 2004 Intro to Ruby Slide #23
Prev Next

Accessor functions

Instance variables can't be accessed from outside a class, so you need to write accessor functions to expose a variable to the outside world. To make a "getter" method, just make a member function with the same name as the member variable (though without the @):
     class Pony
         def color
             @color
         end
     end

To make a "setter", put an equals sign after the method name:
     class Pony
         def name=(new_name)
             @name = new_name
         end
     end

Because this is so common, Ruby has a shorthand syntax to create them:
     class MyClass
         attr_reader   :r1, :r2  # creates @r1, r1, @r2, r2
         attr_writer   :w1       # creates @w1, w1=
         attr_accessor :a1       # creates @a1, a1, a1=


Prev Copyright © 2004 Walter C. Mankowski Next