Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object in Ruby without using new

It's possible to create a Complex number in Ruby using

c = Complex.new(1,2)

but, it can be shortened to

c = Complex(1,2)

Is it possible to achieve the same functionality without having to define a function outside the class, like in the example below?

class Bits
  def initialize(bits)
    @bits = bits
  end
end

def Bits(list) # I would like to define this function inside the class
  Bits.new list
end

b = Bits([0,1])

I think Ruby should allow at least one of the proposed constructors below

class Bits
  def initialize(bits)
    @bits = bits
  end

  def self.Bits(list) # version 1
    new list
  end

  def Bits(list)      # version 2
    new list
  end

  def Bits.Bits(list) # version 3
    new list
  end
end
like image 745
Kri-ban Avatar asked Jun 22 '14 12:06

Kri-ban


People also ask

How do you create an object in Ruby?

You can create objects in Ruby by using the method new of the class. The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods. Here, cust1 and cust2 are the names of two objects.

What is self method in 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.

What does .NEW do in Ruby?

The new function in Ruby is used to create a new Enumerator object, which can be used as an Enumerable. Here, Enumerator is an object. Parameters: This function does not accept any parameters.

Does a Ruby class need an initialize method?

The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.


1 Answers

Have this snippet:

def make_light_constructor(klass)
    eval("def #{klass}(*args) #{klass}.new(*args) end")
end

Now you can do this:

class Test
    make_light_constructor(Test)
    def initialize(x,y)
        print x + y
    end 
end

t = Test(5,3)

Yes, I know you're still defining a function outside a class - but it is only one function, and now any class you want can make use of its implementation rather than making one function per class.

like image 112
Voldemort Avatar answered Sep 27 '22 20:09

Voldemort