是否可以在ruby中包含每个对象的模块?

时间:2023-01-15 21:55:26

Is it possible to include module per instance in ruby?

是否可以在ruby中包含每个实例的模块?

i.e. in Scala, you can do the following.

即在Scala中,您可以执行以下操作。

val obj = new MyClass with MyTrait

can you do something similar in ruby, maybe something similar to following?

你可以在ruby中做类似的事情,或许类似于以下内容吗?

obj = Object.new include MyModule

2 个解决方案

#1


15  

Yes, you can:

是的你可以:

obj = Object.new
obj.extend MyModule

#2


2  

Yes, see Object#extend. All objects have the extend method, which takes a list of modules as its arguments. Extending an object with a module will add all instance methods from the module as instance methods on the extended object.

是的,请参阅Object#extend。所有对象都有extend方法,它以模块列表作为参数。使用模块扩展对象将从模块添加所有实例方法作为扩展对象上的实例方法。

module Noise
  def cluck
    p "Cluck cluck!"
  end
end

class Cucco
end

anju = Cucco.new
anju.extend Noise
anju.cluck

==> "Cluck cluck!"

#1


15  

Yes, you can:

是的你可以:

obj = Object.new
obj.extend MyModule

#2


2  

Yes, see Object#extend. All objects have the extend method, which takes a list of modules as its arguments. Extending an object with a module will add all instance methods from the module as instance methods on the extended object.

是的,请参阅Object#extend。所有对象都有extend方法,它以模块列表作为参数。使用模块扩展对象将从模块添加所有实例方法作为扩展对象上的实例方法。

module Noise
  def cluck
    p "Cluck cluck!"
  end
end

class Cucco
end

anju = Cucco.new
anju.extend Noise
anju.cluck

==> "Cluck cluck!"