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
A Ruby module can contain classes and other modules, which means you can use it as a namespace.
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.
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.
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.
Yes, you can:
obj = Object.new
obj.extend 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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With