为什么我无法从 ruby 中同一模块的类中访问模块函数?

  • 本文关键字:模块 访问 函数 ruby ruby
  • 更新时间 :
  • 英文 :


我对ruby的访问规则有一些问题。有一次,我认为这样的东西起了作用:

module Foo
def bar(x)
puts "#{x}"
end

class Baz
def initialize(x)
bar(x)
end
end
end
Foo::Baz.new(3)

但不知怎么的,它已经不复存在了。我曾尝试使用self.barFoo.bar声明bar,但都不起作用。我错过了什么?

模块方法的包含不是"自动";,我认为这是因为它会导致意想不到的行为。

您可以尝试将它们作为您提到的类方法,或者包括模块并访问那里的方法:

module Foo
class << self
def bar(x)
puts "#{s}" % x
end
def s
"s1"
end
end
def bar(x)
puts "#{s}" % x
end
def s
"s2"
end

class Baz
include Foo

def initialize(x)
bar(x)
Foo.bar(x)
end
end
end
Foo::Baz.new(3)
# s2
# s1

最新更新