[英]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'sinitialize
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
的源代码:
machine/builtin/class.cpp
machine/builtin/class.cpp
core/src/main/java/org/jruby/RubyClass.java
core/src/main/java/org/jruby/RubyClass.java
topaz/objects/classobject.py
topaz/objects/classobject.py
src/kernel/bootstrap/Class.rb
src/kernel/bootstrap/Class.rb
object.c
(BTW, you will notice that this method is defined in object.c
, not in class.c
. This is one of those reasons I prefer not to look at YARV for implementations details, and instead look at Rubinius, JRuby, IronRuby, or Topaz. They are just much better organized.) object.c
(顺便说一句,你会注意到这个方法是在object.c
定义的,而不是在class.c
。这是我不喜欢查看 YARV 以获取实现细节的原因之一,而是查看 Rubinius, JRuby、IronRuby 或 Topaz。它们的组织要好得多。)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.