From: Dan Doel Date: 2003-08-17T03:17:02+09:00 Subject: Re: Newbie Q: Data encapsulation with Ruby Meino Christian Cramer wrote: > (in general)...but with the getter/setter (especially setter) you > gain more control over what is going in and out. > > A setter could control the validity of the value range... > > (I am not saying, that it is NOT POSSIBLE in ruby to write > setter/getter methods! This is a more general remark on OOP...) > > > Okay, I see where the confusion is. Ruby style doesn't recommend that you write setter/getter methods with names like: setA/getA Instead of setA, you write: def a=(val) @a = val end And instead of getA, you write def a @a end Basically, the private instance variable is called @var_name, the getter is a method named var_name, and the setter is a method named var_name=. You can write these methods yourself, as I have above. All attr_reader and attr_writer do is write a default implementation (basically, the exact forms that I wrote above), to save you some typing. If you want, you can do: def a=(val) if val < 0 raise "a cannot be negative" end # convert from degrees to radians a = val*pi/360 end This is an interesting system, in that you can have one internal variable linked to what looks like multiple pseudo "public" variables. Like: class Angle # this class stores the angle in grads def grads @grads end def grads=(val) @grads = val end def radians @grads*pi/400 end def radians=(val) @grads = val*400/pi; end def degrees @grads*360/400 end def degrees=(val) @grads = val*400/360 end end However, the first two methods here are just straigt setter/getters, so you could write: class Angle attr_reader :grads attr_writer :grads ... end So they're just convenience methods. Hope this helps. - Dan