From: "Jesús Gabriel y Galán" Date: 2011-06-03T01:51:59+09:00 Subject: Re: CORE - Replace "if __FILE__ == $0" with "executed?" On Thu, Jun 2, 2011 at 6:34 PM, Chad Perrin wrote: > On Thu, Jun 02, 2011 at 10:51:46PM +0900, Peter Zotov wrote: >> >> It failed because __FILE__ is not a constant: it is a special lexical >> construct which is replaced by just a string containing the filename at >> the point of _loading_ the file, i.e. even before the execution begins. >> You simply cannot access it in any way after the file was loaded. >> >> You can still implement it this way (note that it may not work on >> implementations other >> than MRI): > > [snip] > > This seems to work just fine: > >    module Kernel >      def executed? >        __FILE__ == $0 >      end >    end > >    if executed? >      puts 'awesomesauce' >    else >      puts 'failsauce' >    end > > What am I missing in the constraints of the request? He wants to have the definition of the executed? method in a different file, which gets required in his main file, and the problem is that __FILE__ then it's evaluated to the name of the other file, not the main file. A solution, which I don't know if it feels clean enough would be to pass that to the method: #executed.rb module Kernel def executed? file=__FILE__ file == $0 end end #main.rb require 'executed' if executed? __FILE__ puts "Executed" else puts "Loaded" end $ ruby main.rb Executed $ ruby -rmain -e "" Loaded Jesus.