2

我正在模块内写一些类:

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 中调用?

4

3 回答 3

4

就好像你写:

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。继承实例方法只有两种方式:

  1. class C < super_classsuper_class返回类的表达式 在哪里

  2. 包括一个模块:

    class C
      include <some module>
    

有关超类链的说明,请参阅继承如何在 Ruby 中工作?Ruby:模块、Mixins 和 Blocks 令人困惑?

于 2013-01-24T14:12:04.333 回答
3

Namespaces in Ruby don’t work the way you seem to think.

  1. 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.

  2. 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.

于 2013-01-24T12:55:17.103 回答
2
class A::B::C
  include A::B
end
于 2013-01-24T12:24:12.243 回答