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


当前回答

属性访问器attr_accessor提供了两个免费方法。

就像在Java中,它们被称为getter和setter。

很多答案都给出了很好的例子,所以我就简单点。

# the_attribute

and

# the_attribute =

在旧的ruby文档中,#表示方法。 它还可以包含一个类名前缀… MyClass # my_method

其他回答

属性访问器attr_accessor提供了两个免费方法。

就像在Java中,它们被称为getter和setter。

很多答案都给出了很好的例子,所以我就简单点。

# the_attribute

and

# the_attribute =

在旧的ruby文档中,#表示方法。 它还可以包含一个类名前缀… MyClass # my_method

Attr_accessor(如@pst所述)只是一个方法。它的作用是为你创建更多的方法。

这段代码:

class Foo
  attr_accessor :bar
end

等价于下面的代码:

class Foo
  def bar
    @bar
  end
  def bar=( new_value )
    @bar = new_value
  end
end

你可以自己用Ruby编写这样的方法:

class Module
  def var( method_name )
    inst_variable_name = "@#{method_name}".to_sym
    define_method method_name do
      instance_variable_get inst_variable_name
    end
    define_method "#{method_name}=" do |new_value|
      instance_variable_set inst_variable_name, new_value
    end
  end
end

class Foo
  var :bar
end

f = Foo.new
p f.bar     #=> nil
f.bar = 42
p f.bar     #=> 42

基本上,它们伪造了Ruby所不具备的公开可访问的数据属性。

另一种理解它的方法是通过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

它只是一个为实例变量定义getter和setter方法的方法。一个示例实现如下:

def self.attr_accessor(*names)
  names.each do |name|
    define_method(name) {instance_variable_get("@#{name}")} # This is the getter
    define_method("#{name}=") {|arg| instance_variable_set("@#{name}", arg)} # This is the setter
  end
end