From: James French Date: 2009-04-09T00:34:16+09:00 Subject: Re: performing an action only the first time a function called I have to admit though, I don't understand the 'wrapped, count = self, 0' line... -----Original Message----- From: James French [mailto:James.French@naturalmotion.com] Sent: 08 April 2009 16:13 To: ruby-talk ML Subject: Re: performing an action only the first time a function called I see I still have some way to go with ruby :) Nice! Can't believe how quick you knocked that up... -----Original Message----- From: James Coglan [mailto:jcoglan@googlemail.com] Sent: 08 April 2009 15:43 To: ruby-talk ML Subject: Re: performing an action only the first time a function called > 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