0

如果创建一个类Foo并定义一个被调用的函数initialize 一个被调用的函数new怎么办?

稍后,如果我编写代码foo = Foo.new,将运行哪个函数?由于initialize应该在声明时调用该函数new

编辑:

为了澄清:

class Foo
    def new
    end
end

这就是我所说的那种事情。

4

2 回答 2

4

If you defined new on the class, it would call your function and override the typical new method which would create a new instance of the class. It's better if you don't override it at all, but you can still do it and get away with it in Ruby because Ruby's nice like that.

If you still want a new instance of the class after that, you can call Foo.allocate to get that. Then you can call initialize on that object manually to trigger any initialization events.

于 2013-02-04T22:13:58.050 回答
2

new做的时候不会调用手动定义的函数,Foo.new因为手动定义new的函数是实例函数。Foo.new正在调用一个函数。

class Foo
    def new
        puts 'new!'
        123
    end

    def initialize
        puts 'initialize'
    end
end

c = Foo.new
puts c  #this will print "#<Confusion:0xb75b20f4>"
c.new   #this will print "new!"

编辑:

但是,如果我这样做了:

class Foo
    def Foo.new
    end
end

然后我们会遇到@Ryan 指出的问题。

于 2013-02-04T22:16:47.400 回答