From: Rick DeNatale Date: 2008-04-24T02:47:23+09:00 Subject: Re: Ruby and object paradigm On Wed, Apr 23, 2008 at 10:06 AM, Albert Schlef wrote: > BTW, you _can_ implement if/else in Ruby using methods alone. > > That smalltalk line can be written in Ruby as... > > (self == 0).ifelse lambda { 1 }, lambda { self * ((self-1).factorial) } > > ...if you bother to define an 'ifelse' method for Object: > > class Object > def ifelse(true_block, false_block) > if self > true_block.call > else > false_block.call > end > end > end Sort of a circular definition though. In the spirit of the Smalltalk implementation it would be more like: class Object def if_else(true_proc, false_proc) true_proc.call end end class NilClass def if_else(true_proc, false_proc) false_proc.call end end class FalseClass def if_else(true_proc, false_proc) false_proc.call end end And the call would need to be something like: expr.if_else lambda { "True"}, lambda {"False"} or Proc.new... if you wanted to say return from one of the legs, i.e. the Smalltalk expr ifTrue:[^"True"] ifFalse:["Whatever"] would need to be expr.if_else( Proc.new {return "True"}, lambda {"Whatever"}) -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/