I have a module which exists to be included in two similar classes. Some of the methods to be included in the module for identical use by both classes return a new instance.
But how to I encode in the module that the constructor for the containing class should be called?
A simplified example:
module Point3D
def initialize(x,y,z)
@x = x
@y = y
@z = z
end
def * (scalar)
<myclass>.new(@x * scalar, @y * scalar, @z * scalar)
end
end
class Vertex
include Point3D
end
class Vector
include Point3D
end
So in the definition of *
how would i call the constructor such that in the context of the Vertex class it returned a new Vertex and in the context of the Vector class it returned a new Vector without redeclaring all such methods in each class?
One practical use for self is to be able to tell the difference between a method & a local variable. It's not a great idea to name a variable & a method the same. But if you have to work with that situation, then you'll be able to call the method with self. method_name .
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.
Ruby doesn't support multiple inheritance. Modules eliminate the need of multiple inheritance using mixin in Ruby. A module doesn't have instances because it is not a class. However, a module can be included within a class.
In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class.
You can call 'class' method to get the class of obj.
For this case, it's
def * (scalar)
self.class.new(...)
end
Use self.class to get the object of the class where the module is included.
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