On Sun, Jun 5, 2011 at 5:33 PM, Clifford Heath <clifford.heath / gmail.com>wrote: > On 05/06/2011, at 11:29 PM, Benoit Daloze wrote: > >> Clifford Heath wrote: >> >>> That is, the problem is that it's not obvious to a newcomer that __FILE__ >>> means >>> the current source-code file, or that $0 means the name of the script >>> being executed. Especially the latter... >>> >> >> $PROGRAM_NAME is an alias for $0. >> But "if __FILE__ == $PROGRAM_NAME" is quite long. >> > > Length is not a problem, if the text includes the meaning. > > Things that are used often should be succinct, and the reader's > knowledge should be assumed. Things that are used only a > few times in a program do not need to be succinct. > > To use an API call requires that the user knows (or looks up) > the meaning. This kind of semantic hiding is completely > unnecessary and *counter-productive*. > In my opinion, the reason for adding executed? or something like this is because __FILE__ == $PROGRAM_NAME does not reliably test whether a program has been invoked directly from Ruby or is required/loaded. The sources of variability (and thus unreliability) stem from *both* sides of the "==". First, __FILE__ can be a relative file name. Consider this code in two files /tmp/foolme.rb and /tmp/foolme/foolme.rb: # File /tmp/foolme.rb puts "++1 #{__FILE__}" Dir.chdir('/tmp/foolme') { require './foolme' } # File /tmp/foolme/foolme.rb puts "++2 #{__FILE__}" If you run this on MRI 1.8 or Rubinius 1.8 (e.g. 1.2.3) you will get this output: ++1 ./foolme.rb ++2 ./foolme.rb On MRI 1.9 the output is different. On the other side of the ==, you have the problem that $0 or $PROGRAM_NAME can be set. Thus, if it is useful to be able to tell if a file has been invoked initially as main script, then it would be nice have a reliable and way to do so. I think it useful to distinguish the two in order to more reliably support the style of programming I use. I generally put little demo code, at the bottom of each class or module. You can think of this demo code as something like unit test code; often it is modified and becomes unit test code. But demo code and test code have a slightly different focus, since demoing and testing are different. > Clifford Heath. > > >