Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a .rb file from IRB?

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 my current directory.

My question is how do I run a .rb file in IRB?
And do I have to be in the directory where this .rb file lives when I run it 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 but at least it didn't give any errors.

I also tried a whole bunch of other stuff that plain gave me errors. So I don't think I can solve this myself and googling the matter didn't help at all.

I am running Leopard.

like image 551
Katrina Avatar asked May 27 '11 08:05

Katrina


People also ask

How do I run a code in IRB?

To use it, you launch the irb executable and type your Ruby code at the prompt. IRB evaluates the code you type and displays the results. IRB gives you access to all of Ruby's built-in features, as well as any libraries or gems you've installed.

How do I open a Ruby file in IRB?

If you only need to load one file into IRB you can invoke it with irb -r ./your_file. rb if it is in the same directory. This automatically requires the file and allows you to work with it immediately. If you want to add more than just -r between each file, well that's what I do and it works.


2 Answers

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 
like image 119
J-_-L Avatar answered Sep 22 '22 17:09

J-_-L


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.

like image 39
Gabriel Lidenor Avatar answered Sep 23 '22 17:09

Gabriel Lidenor