Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having multiple constructors in ruby [duplicate]

is there a way to have multiple “initialize” methods in ruby? For example: one method excepting one argument while another excepts three ?

Something like

 class One
  def initialize (a)
    puts a
  end
  def initialize_1 (a,b)
    puts a ,b 
  end
end
like image 262
13driver Avatar asked Mar 22 '13 15:03

13driver


People also ask

Can you have multiple constructors with the same name?

In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading.

Can you have multiple constructors for an object?

A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.

Can two constructors have the same parameters?

The technique of having two (or more) constructors in a class is known as constructor overloading. A class can have multiple constructors that differ in the number and/or type of their parameters. It's not, however, possible to have two constructors with the exact same parameters.

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.


1 Answers

initialize is actually not a constructor. You can indeed have two constructors.

class One
  singletonclass.class_eval{alias old_new :new}
  def self.new a
    puts a
    old_new
  end
  def self.new_1 a, b
    puts a, b
    old_new
  end
end
like image 193
sawa Avatar answered Sep 22 '22 16:09

sawa