Is it possible to include module per instance in ruby?
i.e. in Scala, you can do the following.
val obj = new MyClass with MyTrait
can you do something similar in ruby, maybe something similar to following?
obj = Object.new include MyModule
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.
module Noise
def cluck
p "Cluck cluck!"
end
end
class Cucco
end
anju = Cucco.new
anju.extend Noise
anju.cluck
==> "Cluck cluck!"