Require file without executing code?

前端 未结 3 734
走了就别回头了
走了就别回头了 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:42

    Is it possible to load a file without having it to run the code?

    No, everything in a ruby file is executable code, including class and method definitions (you can see this when you try to define a method inside an if-statement for example, which works just fine). So if you wouldn't execute anything in the file, nothing would be defined.

    You can however tell ruby that certain code shall only execute if the file is run directly - not if it is required. For this simply put the code in question inside an if __FILE__ == $0 block. So for your example, this would work:

    file.rb

    def method
      puts "This won't be outputted."
    end
    if __FILE__ == $0
      puts "This will not be outputted."
    end
    

    main.rb

    require "./file"
    

提交回复
热议问题