When we are writing a module, it is more or less necessary to run the file directly or execute some methods, but this is not good for when the module is require or include, in Ruby, is there any distinction between running from the current file or being called by the Require object file?
Python can
Like Python, for example.
Copy Code code as follows:
if __name__ = = ' __main__ ':
Print "From direct running"
Ruby, of course, can.
For programmers everywhere for the sake of the idea of happiness programming ruby, of course, can be distinguished. The principle is to determine whether the startup file is a module's code file.
Copy Code code as follows:
If __file__ = $
Puts ' called from direct running '
End
As an example
Tool class module UTILS.RB
Copy Code code as follows:
Module Utils
Class StringUtils
def self.test
Puts "test method myfile=" + __file__ + '; load from ' + $
End
End
End
If __file__ = $
Puts ' called from direct running '
Utils::stringutils.test ()
End
Run directly, the result is that if condition is set up, the output is executed
Copy Code code as follows:
20:04:37-androidyue~/rubydir/test$ Ruby Utils.rb
Called from direct running
Test method Myfile=utils.rb;load from UTILS.RB
Reference to Utils class TEST.RB
Copy Code code as follows:
Require './utils '
Utils::stringutils.test ()
Running results, the conditions for introducing modules are not valid, and there is no output called from direct running
Copy Code code as follows:
20:08:07-androidyue~/rubydir/test$ Ruby Test.rb
Test method Myfile=/home/androidyue/rubydir/test/utils.rb;load from TEST.RB