21

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
Yeonho
  • 3,629
  • 4
  • 39
  • 61

2 Answers2

24

Yes, you can:

obj = Object.new
obj.extend MyModule
Henrik N
  • 15,786
  • 5
  • 82
  • 131
7

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!"
Ryan Plant
  • 1,037
  • 1
  • 11
  • 18