Methods for distinguishing runtime sources in Ruby and Ruby for distinguishing runtime Methods

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.