Ruby-on-rails rails 中的 initialize 方法有什么作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13216976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:59:07  来源:igfitidea点击:

What does the initialize method in rails do

ruby-on-railsruby-on-rails-3attributes

提问by jason328

I'm trying to wrap my head around the purpose of using the initialize method. In Hartl's tutorial, he uses the example..

我试图围绕使用 initialize 方法的目的。在 Hartl 的教程中,他使用了示例..

def initialize(attributes = {})
   @name = attributes[:name]
   @email = attributes[:email]
end

Is initialize setting the instance variables @nameand @emailto the attributes, and if so why do we have the argument attributes = {}?

初始化设置实例变量@name@email属性,如果是这样,为什么我们有参数attributes = {}

回答by Michael Shimmins

Ruby uses the initializemethod 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:

Ruby 使用该initialize方法作为对象的构造函数。它是 Ruby 语言的一部分,并非特定于 Rails 框架。当您实例化一个新对象时会调用它,例如:

@person = Person.new

Calling the newclass level method on a Classallocates a type of that class, and then invokes the object's initializemethod:

new在 a 上调用类级别的方法会Class分配该类的类型,然后调用该对象的initialize方法:

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 initializemethod 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 initializemethod, you need to define your own version of it.

所有对象都有一个initialize不接受任何参数的默认方法(您不需要编写一个 - 您会自动获得它)。如果你想让你的对象在initialize方法中做一些不同的事情,你需要定义你自己的版本。

In your example, you are passing a hash to the initializemethod which can be used to set the default value of @nameand @email.

在您的示例中,您将散列传递给initialize可用于设置@nameand的默认值的方法@email

You use this such as:

您使用它,例如:

@person = Person.new({name: 'John Appleseed', email: '[email protected]'})

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 attributeswill be an empty hash, and thus both @nameand @emailwill be nilvalues as no value exists for those keys (:nameand :email).

初始化程序具有属性attributes = {}的默认值(将默认值设置为 ampty 哈希 - {})的原因是您也可以调用它而无需传递参数。如果你不”指定参数,那么attributes将是一个空的哈希,因此双方@name@emailnil作为存在这些键(无值值:name:email)。