Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to include module per object in ruby?

Tags:

ruby

mixins

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
like image 1000
Yeonho Avatar asked Dec 18 '14 08:12

Yeonho


People also ask

Can a module contain a class Ruby?

A Ruby module can contain classes and other modules, which means you can use it as a namespace.

Can modules inherit Ruby?

The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways.

How do I import a module into Ruby?

include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.

Is everything an object in Ruby?

Practically everything in Ruby is an Object, with the exception of control structures. Whether or not under the covers a method, code block or operator is or isn't an Object, they are represented as Objects and can be thought of as such.


2 Answers

Yes, you can:

obj = Object.new
obj.extend MyModule
like image 154
Henrik N Avatar answered Oct 20 '22 08:10

Henrik N


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!"
like image 26
Ryan Plant Avatar answered Oct 20 '22 07:10

Ryan Plant