从 class 内部使用 attr_accessor?

Using attr_accessor from inside class?

我试图在定义它的 class 内部使用 attr_accessor,但无济于事。为什么这不起作用?

我希望以下内容在 IRB 中输出 "new":

irb(main):016:0> foo = StringClass.new
=> #<StringClass:0x2fbf2c0 @thing="old">
irb(main):017:0> foo.output
old
=> nil
irb(main):018:0> foo.change
=> "new"
irb(main):021:0> foo.output
old
=> nil

实现如下:

class StringClass
  def initialize
    @thing = "old"
  end

  attr_accessor :thing

  def output
    puts thing
  end

  def change
    thing = "new"
  end
end

我可以看到 thing= 方法已定义。我不明白为什么当我尝试更改值时没有调用该方法。

试试这个 -

class StringClass
   ......

   def change
     self.thing = "new"
   end
 end
  1. foo = StringClass.new
  2. foo.change => "new"

也就是说,因为这些方法应该用 self:

调用
class StringClass
  def initialize
    @thing = "old"
  end

  attr_accessor :thing

  def output
    puts self.thing
  end

  def change
    self.thing = "new"
  end
end