NameError on constructor in ruby
I'm trying to set a default value in an instance variable. I'm doing:
module MyModule::MyOtherModule
class MyClass
开发者_如何学运维 attr_accessor :point
def initialize
@point = Point.new(0,1)
end
end
end
module MyModule
class Point
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
end
end
Point is also a class I wrote. The funny thing is that whenever I run this sample, I get:
uninitialized constant MyModule::MyOtherModule::MyClass::Point (NameError)
But if I move the assignment to another method instead of the constructor - say, foo - the error doesn't happen. I think this suggests it's not something related to module location. So, what's wrong?
Module =! module
Class =! class
In this case Module and Class are constants in Ruby so in essence this code is incorrect. Proper module and class constructs are downcased. That's the first.
Second, to answer your question, we would need to look on how actually Point class definitions looks, and how do you instantiate MyClass. In the moment message is clear: uninitialized constant
, it cannot find Point anywhere in a scope.
EDIT
module MyModule
module MyOtherModule
class MyClass
attr_accessor :point
def initialize
#as mentioned by nas
@point = MyModule::Point.new(0,1)
end
end
end
end
module MyModule
class Point
attr_accessor :x, :y
def initialize(x, y)
@x = x
@y = y
end
end
end
obj = MyModule::MyOtherModule::MyClass.new()
puts obj.point.x #=> 0
puts obj.point.y #=> 1
Since your Point class is in scope of MyModule so best practice would be to access it like so MyModule::Point
. A slight change in your MyClass constructor would be:
def initialize
@point = MyModule::Point.new(0,1)
end
精彩评论