From: Daniel Berger Date: 2006-02-03T05:17:03+09:00 Subject: Re: ruby-dev summary 28206-28273 ara.t.howard@noaa.gov wrote: > On Thu, 2 Feb 2006, Minero Aoki wrote: > >> [ruby-dev:28217] ANDCALL operator >> >> Nobuyoshi Nakada suggested a new operator `&?' (this notation is >> temporary) >> which evaluates left-hand-side expression, and if it is true then call >> right-hand-side method. For example: >> >> if a[1] and a[1].strip.empty? >> || >> if a[1] &? strip.empty? >> >> h["key"] and h["key"].dispatch >> || >> h["key"] &? dispatch >> >> The motivation of this operator is to avoid duplication of expression. >> >> Takaaki Tateishi proposed another idea, Object#nil? with block >> (again, this name is temporary). >> >> a[1].nil? {|str| str.strip.empty? } >> h["key"].nil? {|h| h.dispatch } >> >> This issue is still open. > > > > suggestion: > > > harp:~ > cat a.rb > # > # predicate methods to avoid double evaluation of expr > # > module Kernel > def iff?(a, &b) a.instance_eval &b if a end > alias_method "if?", "iff?" > def iff!(a, &b) a.instance_eval &b unless a end > alias_method "if!", "iff!" > end > > a = [ 42 ] > b = [ false ] > > # > # if, and only if > # > > iff?(a.first){ p self } > > # > # if, and only if not > # > > iff!(b.first){ p self } > > > > harp:~ > ruby a.rb > 42 > false > > > kind regards. > > -a (Reposted to ruby-talk) Nice. If only "if" were a Kernel method that we could tie it to back to "if/else" constructs somehow: iff a.first ... else ... end Cue the Smalltalk weenies... Regards, Dan