How to run a .rb file from IRB?
Asked Answered
P

3

98

I am starting out with Ruby on Rails. I am currently going through a tutorial that says that I have to run a .rb file from IRB to create a .xml file in my current directory.

My question is how do I run a .rb file in IRB?

I tried the following: just typing irb on the command line in the directory of the file. That starts an IRB session as far as I understand.
Then I typed

irb filename.rb

which went through, but didn't create anything in the current directory.

Pinkston answered 27/5, 2011 at 8:46 Comment(0)
S
185

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
Scriven answered 27/5, 2011 at 8:54 Comment(3)
to require it from irb you need to provide the fully qualified path, thus: require '~/myrubystuff/coolstuff.rb' instead of just require 'coolstuff'Wanyen
I was able to require fileutils by name alone, no directory path needed. I'm sure it's environment dependent and not everyone will need to use the qualified path.Angeles
note local variables aren't available automatically, although there are easy workarounds #2699824Babcock
E
9

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.

Echidna answered 9/5, 2019 at 14:5 Comment(2)
that was what i was actually searching for, thanks a lot!Marrano
This gives access only to functions, not variables defined in the file.Homily
N
3

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.

Nodular answered 25/8, 2013 at 14:31 Comment(2)
But by loading the file you can access variables defined there. Handy when troubleshooting or playing with a library.Anzovin
@Nodular This was just what I was looking for. Thanks!Acquittal

© 2022 - 2024 — McMap. All rights reserved.