如何扩展模块并直接引用其方法 Ruby
How to extend a module and also directly reference its methods in Ruby
我有以下代码
module Hello
def hello_world
puts "Hello World"
end
end
class Test
extend Hello
end
test = Test
test.hello_world
Hello.hello_world
这有以下输出
Hello World
main.rb:13:in `<main>': undefined method `hello_world' for Hello:Module (NoMethodError)
如何让上面的代码工作,以便 test.hello_world
和 Hello.hello_world
都能工作?
Hello
不响应 hello_world
因为 hello_world
不是 class 方法。您可以通过使用 self
扩展 Hello
模块来获得所需的行为,如下所示:
module Hello
extend self
def hello_world
puts "Hello World"
end
end
class Test
extend Hello
end
test = Test
test.hello_world #=> Hello World
Hello.hello_world #=> Hello World
我有以下代码
module Hello
def hello_world
puts "Hello World"
end
end
class Test
extend Hello
end
test = Test
test.hello_world
Hello.hello_world
这有以下输出
Hello World
main.rb:13:in `<main>': undefined method `hello_world' for Hello:Module (NoMethodError)
如何让上面的代码工作,以便 test.hello_world
和 Hello.hello_world
都能工作?
Hello
不响应 hello_world
因为 hello_world
不是 class 方法。您可以通过使用 self
扩展 Hello
模块来获得所需的行为,如下所示:
module Hello
extend self
def hello_world
puts "Hello World"
end
end
class Test
extend Hello
end
test = Test
test.hello_world #=> Hello World
Hello.hello_world #=> Hello World