Methods for distinguishing runtime sources in Ruby and Ruby for distinguishing runtime Methods
When writing a module, we need to directly run this file or execute some methods, but this is not good for this module when it is require or include. In ruby, is there a distinction between running from the current file or being called by the target file of require?
Python can
For example, Python
Copy codeThe Code is as follows:
If _ name _ = '_ main __':
Print "from direct running"
Ruby, of course.
For programmers everywhere, Ruby with happy programming concepts can certainly be different. The principle is to determine whether the Startup file is a module code file.
Copy codeThe Code is as follows:
If _ FILE _ = $0
Puts 'called from direct running'
End
For example
Tool module utils. rb
Copy codeThe Code is as follows:
Module Utils
Class StringUtils
Def self. test
Puts "test method myfile =" + _ FILE _ + '; load from' + $0
End
End
End
If _ FILE _ = $0
Puts 'called from direct running'
Utils: StringUtils. test ()
End
Run the command directly. The result is that the if condition is true and the output is executed.
Copy codeThe Code is 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 Utils class test. rb
Copy codeThe Code is as follows:
Require './utils'
Utils: StringUtils. test ()
Running result. The conditions for introducing the module are not true and no called from direct running is output.
Copy codeThe Code is as follows:
20:08:07-androidyue ~ /Rubydir/test $ ruby test. rb
Test method myfile =/home/androidyue/rubydir/test/utils. rb; load from test. rb