Reputation: 88
I am experimenting with ruby (2.4.1p111) and with the load method and it does have some strange behavior:
I have two files:
mytest.rb:
class MyClass
def self.greet(param)
puts "Got called: #{param}"
end
greet 'Called locally'
load "./testld.rb"
end
and the loaded file:
testld.rb:
greet 'Called by load'
I understood from documentation that the loaded code from testld.rb and the method call right in the MyClass should behave the same. Instead, I am getting:
-bash-4.2$ ruby mytest.rb
Got called: Called locally
/Blacksmith/RB/testld.rb:1:in `<top (required)>': undefined method `greet'
for main:Object (NoMethodError)
from mytest.rb:9:in `load'
from mytest.rb:9:in `<class:MyClass>'
from mytest.rb:1:in `<main>'
Any idea what I do wrong?
Upvotes: 0
Views: 170
Reputation: 168199
Wherever you load a file, the loaded file is always evaluated within the main environment. The value of self
in the main environment of testld.rb
is the main environment of the entire script. Hence, your
greet 'Called by load'
is not equivalent to
MyClass.greet 'Called by load'
as you expected.
Upvotes: 1
Reputation: 2106
You need to call MyClass.greet
in testld.rb
, that is because greet
is a class method defined in the class MyClass
.
Here is documentation for class methods.
Upvotes: 2