我正在模块内写一些类:
module A
end
module A::B
def foo
print "foo"
end
end
class A::B::C
end
A::B::C.new.foo # => NoMethodError: undefined method `foo' for #<A::B::C...>
如何在模块 B 中定义方法以在类 C 中调用?
就好像你写:
module A::B
def foo
print "foo"
end
class C
end
print 'C.instance_methods : '; p C.instance_methods(false)
#=> C.instance_methods : []
end
C
不会自动继承foo
。继承实例方法只有两种方式:
class C < super_class
super_class
返回类的表达式 在哪里
包括一个模块:
class C
include <some module>
有关超类链的说明,请参阅继承如何在 Ruby 中工作?和Ruby:模块、Mixins 和 Blocks 令人困惑?
Namespaces in Ruby don’t work the way you seem to think.
There is no such thing as a “namespace method”. A::B#foo
is an instance method on the module A::B
—which is a module named B
in the namespace of A
.
Namespaces modules/classes have no special relationship of inheritance between them. They are purely organizational in nature, except when defined the long way (e.g. module A; module B; end; end
) when they can affect lexical scope.
If you want to get methods of A::B
in A::B::C
, you must include A::B
in A::B::C
, just like you would anywhere else. You have to do this because, as said above, there's nothing special about a namespaced module/class, it is treated the same as any other.
class A::B::C
include A::B
end