From: James Coglan Date: 2009-04-08T23:43:05+09:00 Subject: Re: performing an action only the first time a function called --001636c5b1840b9e8b04670c262c Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit > Could anyone suggest an elegant way of doing something like: > > $directXSDKBootstrapped = false > > def bootstrapDirectXSDK > if !$directXSDKBootstrapped > bootstrapBuildToolsDirectory("DirectX/#{DIRECTX_VERSION}") > $directXSDKBootstrapped = true > $directXSDKBootstrapped.freeze > end > end One way of doing this is as follows: class Proc def runs(n) wrapped, count = self, 0 lambda { |*args| count += 1 count <= n ? wrapped.call(*args) : nil } end end >> foo = lambda { |arg| puts arg }.runs(3) #=> # >> foo['look!'] look! => nil >> foo['look!'] look! => nil >> foo['look!'] look! => nil >> foo['look!'] => nil Notice nothing is printed the fourth time. So using this, you could write you function as: bootstrapDirectXSDK = lambda { bootstrapBuildToolsDirectory("DirectX/#{DIRECTX_VERSION}") }.runs(1) Which will only allow its contents to be executed once. -- James Coglan http://github.com/jcoglan --001636c5b1840b9e8b04670c262c--