From: Daniel N Date: 2010-04-12T10:13:26+09:00 Subject: Re: attr_accessor, but for a boolean --000e0cd48316093c120483ffda15 Content-Type: text/plain; charset=ISO-8859-1 On 12 April 2010 11:10, Aaron Patterson wrote: > On Mon, Apr 12, 2010 at 10:00:06AM +0900, Albert Schlef wrote: > > Let's say I have this code: > > > > class Mambo > > attr_accesstor :safe > > end > > > > Now, > > > > 'safe', in my case, is a boolean. Problem is, the getter will be named > > 'safe', whereas I want it to be 'safe?'. > > > > In other words, how do I make the getter 'safe?' and the setter 'safe' > > ? > > In situations like this, I make two "getters" and leave the assignment > alone. Other ruby programmers expect your "setters" to be in the form > of "obj.safe = true", not "obj.safe(true)". > > Try something like this: > > class Mambo > attr_accesstor :safe > alias :safe? :safe > end > > Here it is in action: > > irb(main):001:0> class Mambo > irb(main):002:1> attr_accessor :safe > irb(main):003:1> alias :safe? :safe > irb(main):004:1> end > => nil > irb(main):005:0> m = Mambo.new > => # > irb(main):006:0> m.safe = true > => true > irb(main):007:0> m.safe? > => true > irb(main):008:0> > > -- > Aaron Patterson > http://tenderlovemaking.com/ Unfortunately this doesn't support safe? being boolean always. It could be something other than true false (may not be a problem) If you want to use attr_accessor rather than simply aliasing the method I'd suggest def safe? !!safe end This way the expectation of a ? method to return a boolean is preserved. Cheers Daniel --000e0cd48316093c120483ffda15--