【问题标题】:Using attr_accessor from inside class? [duplicate]在课堂内使用 attr_accessor? [复制]
【发布时间】:2015-08-30 21:45:49
【问题描述】:

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

我希望以下内容在 IRB 中输出“新”:

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= 方法已定义。我不明白为什么当我尝试更改值时没有调用该方法。

【问题讨论】:

  • 谢谢,你说得对,这是重复的。如何最好地解决?
  • 由于您只是在类中引用实例变量,也许最好不要使用 attr_accessor,而只需使用 @ 符号。

标签: ruby attr-accessor


【解决方案1】:

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

class StringClass
  def initialize
    @thing = "old"
  end

  attr_accessor :thing

  def output
    puts self.thing
  end

  def change
    self.thing = "new"
  end
end

【讨论】:

  • 谢谢。我真的不明白为什么,当一个人不必为“正常”定义的方法这样做时。
  • @Deejay - 使用语法“无”self,Ruby 不知道您是在尝试调用方法(您知道,因为您了解上下文),或者只是想创建一个局部变量。如果您不指定 self - 在这种情况下它将创建一个局部变量
【解决方案2】:

试试这个 -

class StringClass
   ......

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 2021-11-05
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多