如何在不使用new的情况下在Ruby中创建对象

Kri*_*ban 6 ruby constructor

可以使用Ruby在Ruby中创建一个复数

c = Complex.new(1,2)
Run Code Online (Sandbox Code Playgroud)

但是,它可以缩短为

c = Complex(1,2)
Run Code Online (Sandbox Code Playgroud)

是否可以实现相同的功能而无需在类外定义函数,如下例所示?

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])
Run Code Online (Sandbox Code Playgroud)

我认为Ruby应该允许至少一个下面提出的构造函数

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
Run Code Online (Sandbox Code Playgroud)

ste*_*lag 5

c = Complex(1,2)
Run Code Online (Sandbox Code Playgroud)

实际上是在内核上调用一个方法

  • @DavidUnric 如果需要,您可以使用它。只需创建一个顶级方法(最终作为`Ob​​ject` 上的私有方法,具有相同的效果)。如果你特别想要它,你甚至可以打开“内核”并在那里添加一个方法。 (2认同)

Vol*_*ort 5

有这个片段:

def make_light_constructor(klass)
    eval("def #{klass}(*args) #{klass}.new(*args) end")
end
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

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

t = Test(5,3)
Run Code Online (Sandbox Code Playgroud)

是的,我知道你仍然在一个类之外定义一个函数 - 但它只是一个函数,现在你想要的任何类都可以使用它的实现,而不是每个类创建一个函数.