简体   繁体   English

在ruby中创建一个新对象时,它首先调用什么方法?

[英]When creating a new object in ruby, what method does it call first?

代码块

代码块

When i create the object as soon above, is the method initliase called first?当我如上创建对象时,是否首先调用了 initliase 方法? In PHP, we have something called the constructor with run first whenever an object is created, what if there is more than 1 method in the class, which method is called first in ruby?在 PHP 中,我们有一个叫做构造函数的东西,每当一个对象被创建时,首先运行,如果类中有超过 1 个方法,那么在 ruby​​ 中首先调用哪个方法呢?

Thanks.谢谢。

Class#new is just a normal method like any other method. Class#new只是一个普通方法,就像任何其他方法一样。 It looks a bit like this, although in most implementations it is actually not written in Ruby:它看起来有点像这样,尽管在大多数实现中它实际上不是用 Ruby 编写的:

class Class
  def new(*args, &block)
    new_obj = allocate

    new_obj.initialize(*args, &block)
    # actually, `initialize` is private, so it's more like this instead:
    # new_obj.__send__(:initialize, *args, &block)

    return new_obj
  end
end

The documentation also says it clearly:文档也清楚地说明了这一点:

new(args, …)obj new(args, …)obj

Calls allocate to create a new object of class ’s class, then invokes that object's initialize method, passing it args .调用allocate来创建的类的新对象,然后调用该对象的initialize方法,将其传递给args This is the method that ends up getting called whenever an object is constructed using .new .每当使用.new构造对象时,都会调用此方法。

Here's the source code for Class#new in the various implementations:以下是各种实现中Class#new的源代码:

the initialize method is called whenever you call new .每当您调用new时都会调用initialize方法。

Any other methods declared in that class should be called in your code.应该在您的代码中调用该类中声明的任何其他方法。

For example:例如:

class Example
  def initialize
    #some initialization code here
    puts "initialize method has just been called"
  end

  def foo
    #some foo code
    puts "this is the foo method"
  end 
end 

then, in your code:然后,在您的代码中:

my_obj = Example.new #initialize method will be called here

my_obj.foo #now the foo method will be called

That's about it, good luck!就是这样,祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM