diya
diya

Reputation: 7138

How to require class that is in the same directory in Ruby 1.9.x

I have two ruby files say A and B in certain folder.

The class A code is as follows:

class A
  def self.foo
    puts "foo"
  end
end

A.foo

The class B code is as follows:

class B
  def self.bar
    puts "bar"   
  end
end

B.bar
A.foo

When i try to run class B file, am getting the following error:

bar
b.rb:10:in `<main>': uninitialized constant A (NameError)

I don't want to use modules. So, how do I reference A.foo from class B?

Upvotes: 3

Views: 1734

Answers (1)

Nik O&#39;Lai
Nik O&#39;Lai

Reputation: 3684

I dont know if this answers your question, because I dont fully understand what your intention is.

Your b.rb script is not aware of the class A from a.rb, you know, hence the error. There are several ways to tell b.rb to use a.rb.

  1. you can add to the file b.rb

    require 'a'
    
  2. you can run the b.rb script like this:

    ruby -r a.rb b.rb
    

A side note. In both cases the code in a.rb

    A.foo

is executed as well. You can make that code runnable only when a.rb is directly run, by enclosing the code to run in:

    if __FILE__ == $0
      # code to run when a.rb is executed directly
      A.foo
    end

Upvotes: 2

Related Questions