`if __name__ == '__main__'` equivalent in Ruby

后端 未结 3 1101
天命终不由人
天命终不由人 2020-12-12 14:29

I am new to Ruby. I\'m looking to import functions from a module that contains a tool I want to continue using separately. In Python I would simply do this:



        
3条回答
  •  孤街浪徒
    2020-12-12 15:07

    If stack trace is empty, we can start executing to the right and left. I don't know if that's used conventionally or unconventionally since I'm into Ruby for about a week.

    if caller.length == 0
      # do stuff
    end
    

    Proof of concept:

    file: test.rb

    #!/usr/bin/ruby                                                                 
    
    if caller.length == 0
      puts "Main script"
    end
    
    puts "Test"
    

    file: shmest.rb

    #!/usr/bin/ruby -I .                                                            
    
    require 'test.rb'
    
    puts "Shmest"
    

    Usage:

    $ ./shmest.rb 
    Test
    Shmest
    
    $ ./test.rb
    Main script
    Test
    

提交回复
热议问题