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
Complexthere is both theComplexclass and a separateComplexmethod defined onKernel(so it’s available at the top level), but they are separate things that just share the name. The best you can do is probably put their definitions in the same file.self.BitsvsBits.Bits-> they are almost the same. The disadvantage ofBits.Bitsis that when you change your class's name, you have to change that code too. As for you 3 constructors, they are meant to be aliases of 1 method so why not usealiasoralias_method-like construct? Something that looks likeattr_* :var. I think it is more safe and less repetitive.