From: John W Higgins Date: 2011-06-03T04:12:37+09:00 Subject: Re: CORE - Replace "if __FILE__ == $0" with "executed?" --000e0ce0a9c47190e404a4bf6b07 Content-Type: text/plain; charset=ISO-8859-1 Good Morning, On Thu, Jun 2, 2011 at 6:30 AM, Ilias Lazaridis wrote: > The construct to detect execution of the file (in order to launch main > code) looks like this: > > if __FILE__ == $0 > main > end > > I would like a more elegant code. > I believe the following works but I always get myself into trouble in these areas so I may fall flat on my face here. #test.rb module Kernel def executed? caller[0].split(':')[0] == $0 end end #test2.rb require_relative './test.rb' if executed? puts 'Hello there' else puts 'try again' end #test3.rb require_relative './test2' ruby test2.rb Hello there ruby test3.rb try again #caller holds the stack including the file name of the caller so I believe you can use that instead of __FILE__ in this case. I tested this on ruby 1.9 but I believe it works in 1.8 as well. John --000e0ce0a9c47190e404a4bf6b07--