From: Bob Hutchison Date: 2007-04-13T21:14:01+09:00 Subject: Re: Idiom wanted (now hiring!) On 13-Apr-07, at 2:02 AM, Jonathan wrote: > Is there a cool way to do this without calling the function twice?: > > a = func(b) unless func(b).nil? (AKA) > a = func(b) if func(b) > In lisp there are libraries of utilities that provide what is called 'anaphoric' versions of control structures etc. They are simultaneously widely used and frowned upon. Paul Graham is one of the primary sources of code for this. Ruby can't really do what lisp does, but here is a hacky approximation and some test cases. You'll see why they are frowned upon in the test cases (lisp doesn't do any better than ruby at avoiding errors). Actually, what follows is the output of 'irb --prompt-mode xmp' so, should you want to actually use this stuff, you'll have to clean up the output. I don't think I recommend using it in Ruby by the way. Cheers, Bob module Anaphoric def ifa(v) if v then @it = v yield end end def ifa2(v) if v then yield(v) end end end ==>nil include Anaphoric ==>Object ifa (2 + 3 + 4) do puts "1 -- it #{@it}" end 1 -- it 9 ==>nil ifa2 (2 + 3 + 4) do | it | puts "2 -- it #{it}" end 2 -- it 9 ==>nil ifa (2 + 3 + 4) do puts "3a -- it #{@it}" ifa (99 + 2 + 3 + 4) do puts "3b -- it #{@it}" end puts "3c -- it #{@it}" end 3a -- it 9 3b -- it 108 3c -- it 108 ==>nil ifa2 (2 + 3 + 4) do | it | puts "4a -- it #{it}" ifa2 (99 + 2 + 3 + 4) do | it | puts "4b -- it #{it}" end puts "4c -- it #{it}" end 4a -- it 9 4b -- it 108 4c -- it 108 ==>nil ifa2 (2 + 3 + 4) do | it | puts "5a -- it #{it}" ifa2 (99 + 2 + 3 + 4) do | it2 | puts "5b -- it #{it2}" end puts "5c -- it #{it}" end 5a -- it 9 5b -- it 108 5c -- it 9 ==>nil > -- > Posted via http://www.ruby-forum.com/. > ---- Bob Hutchison -- tumblelog at Recursive Design Inc. -- xampl for Ruby --