From: Gavin Sinclair Date: 2004-02-05T09:45:09+09:00 Subject: Re: two questions >> Second: this is a question on the object orientation consistency of >> ruby (i'm not doubt that ruby is consistent, but i'm only a newbie >> that search for answers...). >> If i declare an instance variale as attr_accessor, i can avoid to >> write getter/setter methods, but how can i surely give a value to a >> variable without writing the relative method?? > > Well... No. The only way you can check the validity of the data being > set by the setter is to write your own setter method. In the case of hours and minutes, I might do something like this: class Time attr_accessor :hours, :minutes def hours=(h) @hours = h _validate end def minutes=(m) @minutes = m _validate end def _validate # raise error if values are outside range end end That way, you're advertising the basic fact that hours and minutes are 'attributes' (which is good for RDoc output, for example), but you're also getting the behaviour you want. In general, though, I prefer to make objects set-once, read-only. That way, you are more assured of their correctness. That's a programming practice you may want to consider. class Time attr_reader :hours, :minutes def initialize(h, m) @hours, @minutes = h, m _validate end def _validate, etc. ... end Cheers, Gavin