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
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.
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.
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.
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.
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
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