【发布时间】:2020-03-11 22:43:21
【问题描述】:
我知道如何在 Ruby 的类中使用模块:
module Calculator
def add(a,b)
a+b
end
end
class Watch
include Calculator
def time
Time.now
end
end
w = Watch.new()
puts w.time # 2020-03-11 22:34:01 +0000
puts w.add(3,5) # 8
但是,有时我可以看到一些模块里面有一个类。例如,在 Rails 中,助手:
module MyModule
class MyClass
def foo
puts 'foo'
end
end
end
这有什么意义?
为什么我要在模块中创建一个类?
【问题讨论】:
-
此外,您可以根据需要在另一个类中定义一个类。这在 Ruby 中并不常见,但有时在有人希望类仅作为父类实例的属性实例化时使用。
-
当你看到一个有类的模块时,原因可能是命名空间。