Require file without executing code?

前端 未结 3 736
走了就别回头了
走了就别回头了 2021-02-07 06:22

Here I have two files:

file.rb

def method
  puts \"This won\'t be outputted.\"
end

puts \"This will be outputted.\"

main.rb

<
3条回答
  •  野的像风
    2021-02-07 06:38

    the if __FILE__ == $0 is nice, but a way more in keeping with ruby's Object Oriented approach is to put all the methods you want access to in a class (as class methods), and then call them from main.rb.

    e.g.

    file.rb

    class MyUtils
        def self.method
            puts "this won't be outputted"
        end
    end
    

    and then in main.rb

    require "/.file.rb"
    

    and when you want to use your utility methods:

    MyUtils.method
    

提交回复
热议问题