How to run a .rb file from IRB?

后端 未结 3 1336
执念已碎
执念已碎 2020-12-12 11:37

I am starting out with Ruby on Rails. I am currently going through a tutorial where it says that I have to run a .rb file from IRB and that that will create a .xml file in m

相关标签:
3条回答
  • 2020-12-12 11:44

    You can "run" a file in irb by just requiring or loading it.

    $ irb
    >> load './filename.rb'
    

    To change your current working directory within irb, you can use FileUtils:

    >> require 'fileutils'
    >> FileUtils.pwd # prints working directory
    >> FileUtils.cd '/path/to/somewhere' # changes the directory
    
    0 讨论(0)
  • 2020-12-12 11:47

    In case you want to have your file loaded in the irb session and you are using Ruby 2+ you can load a file in irb like this:

    irb -r ./the_name_of_your_file.rb
    

    This opens an irb session with the given file loaded.

    Imagine you have file with a class like this:

    class Example
      def initialize(name)
        @name = name
      end
    
      def print__example
        p name
      end
    end
    

    You will be able to use the Example class in the irb session.

    0 讨论(0)
  • 2020-12-12 11:47

    We can just create a .rb file in the directory which you are currently working in using any text editor and type all the code in that and then use the command ruby filename.rb in the terminal, not in the irb, then it shows the output in irb.

    0 讨论(0)
提交回复
热议问题