1

I have a 2 scripts:

test1.rb

require 'test2.rb'
puts "hello"

test2.rb

puts "test"

I'm running this by executing ruby test2.rb test1.rb.

But only test is printed out and not hello.

3
  • Have you looked at the documentation for the ruby command? Commented Aug 20, 2012 at 14:29
  • No, could you please direct me to the relevant documents within the documentation please? Commented Aug 20, 2012 at 14:33
  • 1
    ruby -h: "Usage: ruby [switches] [--] [programfile] [arguments]". So the ruby command takes a single program file, not multiple. Commented Aug 20, 2012 at 14:41

4 Answers 4

2

You only need to run ruby test1.rb and the require statement should pull in test2.rb for you - you don't need to put it on the command line as well. (That will try and run test2.rb, passing the string 'test1.rb' as an argument, which is not what you want here)

Edit: the require statement does not look in the current directory by default when trying to find 'test2.rb'. You can explicitly specify it by changing it to:

require File.dirname(__FILE__) + '/test2.rb'

Sign up to request clarification or add additional context in comments.

4 Comments

When I do that it says theres no such file to load -- test2.rb
File.dirname("C:/Ruby192") + '/test2.rb' doesnt seem to be working either. Error: no such file to load C://test2.rb. Doesnt seem to be forming the path correctly.
when it says __FILE__, you need to actually write that, not 'Ruby192'!
Ashish's answer is also correct - require_relative 'test2.rb' also works for this.
2

in test1.rb do (assuming test2.rb is in same directory, otherwise give its path relative to test1.rb)

require_relative 'test2.rb'
puts "hello"

and on the command line just do ruby test1.rb

1 Comment

yeah its a Kernel function and I use it all the time.
0

This should work as well

require './test2.rb'
puts "hello"

Comments

0

There are some explanation how you can solve your problem, but not what is going wrong.

With ruby test2.rb test1.rb you call the ruby script with the parameter test1.rb.

You have access to the parameters in the constant ARGV.

An example with this script:

puts "test"
puts 'ARGV= %s' % ARGV

The result when you call it:

C:\Temp>ruby test.rb test2.rb
test
ARGV= test2.rb

So you could also write a program like:

require_relative ARGV.first

The first parameter defines a script to be loaded.

Or if you want to load many scripts you could use:

ARGV.each{|script| require_relative script }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.