Reputation: 601
I have two files in folder pc under my home directory.
First file:
class A
class << self
protected
def foo
puts "In foo"
end
end
end
Second file:
class B < A
def bar
self.class.class_eval { foo }
end
end
B.new.bar
My problem is when I run the second file I get the following error:
second.rb:1:in `<main>': uninitialized constant A (NameError)
Why is that?
Upvotes: 0
Views: 996
Reputation: 2469
Try require_relative 'class_a'
or require class_a
.
Note that the file's extension is not included.
Upvotes: 1
Reputation: 26193
This should work, assuming it's all in the same file. If not, you'll need to require
the first file into the next:
# class_b.rb
require 'class_a.rb'
class B < A
def bar
self.class.class_eval { foo }
end
end
B.new.bar
#=> "In foo"
UPDATE:
In order to require the file, you may need to cite the path of the file relative to your current directory. For instance, if class_a.rb
is located in ~/home
and you're running irb (or class_b.rb
is in ~/home
), then you'd include class_a.rb
by citing its relative path as follows:
require './class_a'
Upvotes: 1
Reputation: 176352
B.new.bar
# => In foo
just works fine in my console. I guess you probably forgot to require the file containing A
from the file B
.
In file B
use
require 'a'
(assuming the file containing A
is called a.rb
).
I read the various comments, and just to avoid confusion, here's the full content of the two files.
class_a.rb
class A
class << self
protected
def foo
puts "In foo"
end
end
end
class_b.rb
require_relative 'class_a'
class B < A
def bar
self.class.class_eval { foo }
end
end
puts B.new.bar
And here's how to execute them from the console
$ ruby class_b.rb
In foo
Of course, you should execute the file class_b.rb
, not class_a.rb
or you will not see any result.
Upvotes: 2