如何从 IRB 运行.rb 文件?

我从 Ruby on Rails 开始。我目前正在通过一个教程,它说,我必须运行一个。来自 IRB 的 rb 文件,这将创建一个。在我工作目录的 xml 文件。

我的问题是如何在 IRB 中运行.rb 文件?
当我在 IRB 中运行这个.rb 文件时,我必须在它所在的目录中吗?

我尝试了以下操作: 在文件目录的命令行中键入 irb。据我所知,这会开始一个 IRB 会议。
然后我输入了 irb "filename.rb",它通过了测试,但是没有在工作目录中创建任何东西,但是至少它没有给出任何错误。

我还尝试了一大堆其他的东西,这些东西明显给了我错误。所以我不认为我可以自己解决这个问题,谷歌这件事没有任何帮助。

我在管理美洲豹。

70981 次浏览

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

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.

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.