Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a new instance of self from a ruby instance method

Tags:

ruby

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?

like image 800
Nat Avatar asked Dec 14 '11 12:12

Nat


People also ask

How do you call a self method in Ruby?

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 .

What is self in a class method Ruby?

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.

Can we create instance of module Ruby?

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.

What is an instance method Ruby?

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.


2 Answers

You can call 'class' method to get the class of obj.

For this case, it's

def * (scalar)
  self.class.new(...)
end
like image 164
yedingding Avatar answered Sep 19 '22 04:09

yedingding


Use self.class to get the object of the class where the module is included.

like image 42
Alok Swain Avatar answered Sep 22 '22 04:09

Alok Swain