是什么在轨initialize方法做 [英] What does the initialize method in rails do
问题描述
我试图环绕使用initialize方法的目的,我的头。在哈特尔的教程,他使用的例子。
I'm trying to wrap my head around the purpose of using the initialize method. In Hartl's tutorial, he uses the example..
def initialize(attributes = {})
@name = attributes[:name]
@email = attributes[:email]
end
时的初始化设置实例变量 @name
和 @email
来的属性,如果是这样,为什么我们有说法属性= {}
?
Is initialize setting the instance variables @name
and @email
to the attributes, and if so why do we have the argument attributes = {}
?
推荐答案
红宝石使用初始化
方法作为对象的构造函数。它是Ruby语言,而不是具体到Rails框架的一部分。当你instanstiate一个新的对象,它被调用,例如:
Ruby uses the initialize
method as an object's constructor. It is part of the Ruby language, not specific to the Rails framework. It is invoked when you instanstiate a new object such as:
@person = Person.new
调用在类
分配一个类型的类,然后调用该对象的在新
一流水平的方法初始化
方法:
Calling the new
class level method on a Class
allocates a type of that class, and then invokes the object's initialize
method:
<一个href=\"http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-new\">http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-new
所有的对象都有一个默认的初始化
方法,该方法不接受任何参数(你不需要写一个 - 你得到它自动地)。如果你希望你的对象做一些在初始化
方法不同,你需要定义自己呢版本。
All objects have a default initialize
method which accepts no parameters (you don't need to write one - you get it automagically). If you want your object to do something different in the initialize
method, you need to define your own version of it.
在你的榜样,要传递一个hash到初始化它可以用来设置
@name $的默认值
方法C $ C>和 @email
。
In your example, you are passing a hash to the initialize
method which can be used to set the default value of @name
and @email
.
您使用,如:
@person = Person.new({name: 'John Appleseed', email: 'john@some.net'})
初始化有属性的默认值(属性= {}
设置默认值的ampty哈希的原因 - {}
)是如此,您还可以调用它,而无需传递参数。如果你不'指定参数,那么属性
将是一个空的哈希值,从而既 @name
和 @email
将被存在这些键没有值(无
值:名称
和:电子邮件
)
The reason the initializer has a default value for attributes (attributes = {}
sets the default value to an ampty hash - {}
) is so that you can also call it without having to pass an argument. If you dont' specify an argument, then attributes
will be an empty hash, and thus both @name
and @email
will be nil
values as no value exists for those keys (:name
and :email
).
这篇关于是什么在轨initialize方法做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!