Running another ruby script from a ruby script

后端 未结 7 960
终归单人心
终归单人心 2020-12-01 04:48

In ruby, is it possible to specify to call another ruby script using the same ruby interpreter as the original script is being run by?

For example, if a.rb runs b.rb

相关标签:
7条回答
  • require "b.rb"
    

    will execute the contents of b.rb (you call leave off the ".rb", and there is a search path). In your case, you would probably do something like:

    a.rb:

    require "b.rb";
    b("Hello", "world")
    

    b.rb:

    def b(first, second)
      puts first + ", " + second
    end
    

    Note that if you use require, Ruby will only load and execute the file once (every time you call load it will be reloaded), but you can call methods defined in the file as many times as you want.

    As things get more complex, you will want to move towards an object-oriented design.

    EDIT: In that case, you should look into Ruby threading. A simple example is:

    a.rb:

    require "b";
    t1 = Thread.new{b("Hello", "world");}
    t2 = Thread.new{b("Hello", "galaxy");}
    t1.join
    t2.join
    

    b.rb:

    def b(first, second)
      10.times {
        puts first + ", " + second;
        sleep(0.1);
      }
    end
    
    0 讨论(0)
提交回复
热议问题