Ways to differentiate running sources in Ruby _ruby topics

Source: Internet
Author: User

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

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.