Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

ruby - 什么是Ruby中的attr_accessor?(What is attr_accessor in Ruby?)

I am having a hard time understanding attr_accessor in Ruby.

(我很难理解Ruby中的attr_accessor 。)

Can someone explain this to me?

(谁可以给我解释一下这个?)

  ask by dennismonsewicz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's say you have a class Person .

(假设你有一个Person 。)

class Person
end

person = Person.new
person.name # => no method error

Obviously we never defined method name .

(显然我们从未定义方法name 。)

Let's do that.

(我们这样做。)

class Person
  def name
    @name # simply returning an instance variable @name
  end
end

person = Person.new
person.name # => nil
person.name = "Dennis" # => no method error

Aha, we can read the name, but that doesn't mean we can assign the name.

(啊哈,我们可以读取名称,但这并不意味着我们可以指定名称。)

Those are two different methods.

(这是两种不同的方法。)

The former is called reader and latter is called writer .

(前者称为读者 ,后者称为作家 。)

We didn't create the writer yet so let's do that.

(我们还没有创作作家,所以让我们这样做。)

class Person
  def name
    @name
  end

  def name=(str)
    @name = str
  end
end

person = Person.new
person.name = 'Dennis'
person.name # => "Dennis"

Awesome.

(真棒。)

Now we can write and read instance variable @name using reader and writer methods.

(现在我们可以使用reader和writer方法编写和读取实例变量@name 。)

Except, this is done so frequently, why waste time writing these methods every time?

(除此之外,经常这样做,为什么每次浪费时间写这些方法呢?)

We can do it easier.

(我们可以做得更轻松。)

class Person
  attr_reader :name
  attr_writer :name
end

Even this can get repetitive.

(即使这样也会重复。)

When you want both reader and writer just use accessor!

(当你想要读者和作家都只使用访问者!)

class Person
  attr_accessor :name
end

person = Person.new
person.name = "Dennis"
person.name # => "Dennis"

Works the same way!

(以同样的方式工作!)

And guess what: the instance variable @name in our person object will be set just like when we did it manually, so you can use it in other methods.

(并猜测:我们的person对象中的实例变量@name将被设置,就像我们手动完成时一样,因此您可以在其他方法中使用它。)

class Person
  attr_accessor :name

  def greeting
    "Hello #{@name}"
  end
end

person = Person.new
person.name = "Dennis"
person.greeting # => "Hello Dennis"

That's it.

(而已。)

In order to understand how attr_reader , attr_writer , and attr_accessor methods actually generate methods for you, read other answers, books, ruby docs.

(为了理解attr_readerattr_writerattr_accessor方法如何为您实际生成方法,请阅读其他答案,书籍,ruby文档。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...