本文介绍了在一个类中将attr_accessor和一个initialize方法混合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到如下代码:

class Person
  def initialize(name)
    @name = name
  end
end

我知道这可以让我做person = Person.new之类的事情,并且可以像其他方法一样在类中的其他地方使用@name.然后,我看到了类似的代码:

I understand this allows me to do things like person = Person.new and to use @name elsewhere in my class like other methods. Then, I saw code like:

class Person
  attr_accessor :name
end

...

person = Person.new
person.name = "David"

这两种方法使我无所适从. def initialize(name)有什么特殊用途?我想attr_accessor允许我读写.这意味着它们是两种单独的方法.是的?想要澄清def initializeattr_accessor以及它们如何啮合.

I'm just at a loss with these two methods mesh. What are the particular uses of def initialize(name)? I suppose attr_accessor allows me to read and write. That implies they are two separate methods. Yes? Want clarifications on def initialize and attr_accessor and how they mesh.

推荐答案

initializeattr_accessor彼此无关. attr_accessor :name创建两种方法:

initialize and attr_accessor have nothing to do with each other. attr_accessor :name creates a couple of methods:

def name
  @name
end

def name=(val)
  @name = val
end

如果要在创建对象时设置名称,则可以在初始化程序中进行设置:

If you want to set name upon object creation, you can do it in the initializer:

def initialize(name)
  @name = name
  # or
  # self.name = name
end

但是您不必这样做.创建后,您可以稍后设置名称.

But you don't have to do that. You can set name later, after creation.

p = Person.new
p.name = "David"
puts p.name # >> "David"

这篇关于在一个类中将attr_accessor和一个initialize方法混合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 20:31