From: Morton Goldberg Date: 2007-10-28T08:30:30+09:00 Subject: Re: Truth value evaluating of an object On Oct 27, 2007, at 10:35 AM, Dave River wrote: > I know ruby treat an object as false whenever it is nil or false. > However, I wonder if there are any other ways to change this behavior. > > For example, I define a class called AreYouOk. > class AreYouOk > def initialize(ok) > @ok = ok > end > end > > x = AreYouOk.new(false) > puts "you are ok" if x > > Since x is not nil, ruby prints " you are ok". > However, I want ruby to make the decision based on the @ok instance > variable. Are there any ways to do that? > > I know that there is a method called __bool__ in Python. You can > define > your __bool__ method in your class. The truth value of an object is > based on the return value of __bool__. Does ruby provide similar > mechanism? What you are asking about looks to me like a flag class. class Flag def initialize(state=false) @state = state end def set? @state end def set @state = true end def clear @state = false end end ok = Flag.new puts "you are ok" if ok.set? puts "you are not ok" unless ok.set? ok.set puts "you are ok" if ok.set? puts "you are not ok" unless ok.set? First the string "you are not ok" is printed. After the flag is set, the string "you are ok" is printed. Regards, Morton