我很难理解Ruby中的attr_accessor。 有人能给我解释一下吗?


当前回答

The main functionality of attr_accessor over the other ones is the capability of accessing data from other files. So you usually would have attr_reader or attr_writer but the good news is that Ruby lets you combine these two together with attr_accessor. I think of it as my to go method because it is more well rounded or versatile. Also, peep in mind that in Rails, this is eliminated because it does it for you in the back end. So in other words: you are better off using attr_acessor over the other two because you don't have to worry about being to specific, the accessor covers it all. I know this is more of a general explanation but it helped me as a beginner.

希望这对你有所帮助!

其他回答

attrr -accessor简单地为指定的属性创建getter和setter方法

Attr_accessor非常简单:

attr_accessor :foo

是以下操作的快捷方式:

def foo=(val)
  @foo = val
end

def foo
  @foo
end

它只不过是一个对象的getter/setter

如果你熟悉面向对象的概念,你必须熟悉getter和setter方法。 在Ruby中attr_accessor做同样的事情。

Getter和Setter的一般方式

class Person
  def name
    @name
  end

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

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

Setter方法

def name=(val)
  @name = val
end

Getter方法

def name
  @name
end

在Ruby中的Getter和Setter方法

class Person
  attr_accessor :name
end

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

另一种理解它的方法是通过attr_accessor找出它消除了哪些错误代码。

例子:

class BankAccount    
  def initialize( account_owner )
    @owner = account_owner
    @balance = 0
  end

  def deposit( amount )
    @balance = @balance + amount
  end

  def withdraw( amount )
    @balance = @balance - amount
  end
end

有以下几种方法:

$ bankie = BankAccout.new("Iggy")
$ bankie 
$ bankie.deposit(100)
$ bankie.withdraw(5)

下面的方法会抛出错误:

$ bankie.owner     #undefined method `owner'... 
$ bankie.balance   #undefined method `balance'...

从技术上讲,Owner和balance不是一个方法,而是一个属性。BankAccount类没有def owner和def balance。如果是,那么您可以使用下面的两个命令。但这两个方法都不存在。但是,您可以访问属性,就像通过attr_accessor访问方法一样!!因此有了attr_accessor这个词。属性。访问器。它像访问方法一样访问属性。

添加attr_accessor:balance,:owner允许你读写balance和owner“method”。现在您可以使用最后两个方法。

$ bankie.balance
$ bankie.owner

Attr_accessor只是一个方法。(这个链接应该提供更多关于它如何工作的见解——看看生成的方法对,一个教程应该告诉你如何使用它。)

关键在于,类在Ruby中不是定义(在c++和Java等语言中“只是定义”),而是求值的表达式。在此求值期间,调用attr_accessor方法,该方法反过来修改当前类——记住隐式接收器:self。其中self是此时“打开”的类对象。

对attr_accessor和friends的需求是:

像Smalltalk一样,Ruby不允许在该对象的method1之外访问实例变量。也就是说,不能像在Java甚至Python中那样以x.y形式访问实例变量。在Ruby中,y总是被当作一个要发送的消息(或“要调用的方法”)。因此attr_*方法创建包装器,通过动态创建的方法代理实例@变量访问。 样板很糟糕

希望这能澄清一些细节。快乐的编码。


1严格来说,这并不正确,有一些“技术”围绕这一点,但没有语法支持“公共实例变量”访问。