此代码有什么问题?
module A
def self.foo
puts 'Hello'
end
class B
def test
foo
end
end
end
A::B.new.test
它说:
test.rb:7:in `test': undefined local variable or method `foo' for #<A::B:0x007fcbe29e3580> (NameError)
from test.rb:12:in `<main>'
答案 0 :(得分:2)
你必须写A.foo
来按照定义的方式调用foo。
或者,您可以从foo的定义中删除self.
并在B的定义中编写include A
。这取决于您想要做什么以及您是否希望模块方法具有访问权限到对象的私人数据。
答案 1 :(得分:0)
B
只是A
模块中的另一个常量。模块只是大量的方法和常量,它们内部的类不会自动从它们继承,只停留在该命名空间中。要从A::foo
访问B
方法,您可以:
module A
def self.foo
puts 'Hello'
end
class B
def test
A.foo
end
end
end
A::B.new.test
或者,您可以include
或extend
A
加入B
:
module C
def c_method() 'hey I come from C' end
end
class D
include C # include C's method as instance variable
end
D.new.c_method
=> 'hey I come from C'
class E
extend C # extend C's method into E as class methods
end
E.c_method
=> 'hey I come from C'
module F
# this is a module method, can't be extended or included
def self.f_method() 'hi I come from F' end
end
class G
extend F
include F
def my_method() F.f_method end # you can call it directly anyway
end
G.f_method
=> NoMethodError: undefined method `f_method' for G:Class
G.new.f_method
=> NoMethodError: undefined method `f_method' for #<G:0x0000000c06c668>
G.my_method
=> "hi I come from F"