是什么在轨initialize方法做 [英] What does the initialize method in rails do

查看:116
本文介绍了是什么在轨initialize方法做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图环绕使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆