【问题标题】:Why do I need to call attr_writer methods with `self` to get them to work inside a class? [duplicate]为什么我需要使用 `self` 调用 attr_writer 方法才能让它们在类中工作? [复制]
【发布时间】:2015-08-09 09:40:03
【问题描述】:

这不会输出任何东西:

class Test

  attr_accessor :value

  def run
    set_value
    puts value
  end

  def set_value
    value = 6 # No 'self'
  end
end

Test.new.run

而这输出'6'

class Test

  attr_accessor :value

  def run
    set_value
    puts value
  end

  def set_value
    self.value = 6 # With 'self'
  end
end

Test.new.run

当方法已经定义时,为什么我需要self? Ruby 应该使用方法而不是在 set_value 函数中创建局部变量吗?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您必须使用“@”字符创建一个实例变量:

    value = 6 # create a local variable 'value' and set it to 6
    
    @value = 6 # create an instance variable named 'value' and set it to 6, it will be accessible through the accessor #value
    

    编辑

    self.value = 6 
    

    调用从 attr_accessor 隐式声明的方法 #value=(new_value),它将 @value 实例变量设置为 new_value(可能来自其他范围)

    @value = 6
    

    直接将实例变量设置为 6(只能从实例范围内)

    【讨论】:

      【解决方案2】:

      你总是需要使用 self ,这样 ruby​​ 才能知道你是否没有实例化一个新变量:

      self.value = 6 #ruby knows it's your class variable
      
      value = 6 #ruby thinks you're creating a new variable called value
      

      Assignment Methods

      【讨论】:

        【解决方案3】:

        当方法已经定义时,为什么我需要self

        Assignment Methods

        使用方法分配时,您必须始终有一个接收器。如果你没有接收者,Ruby 假设你正在分配一个局部变量

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-23
          • 2012-07-13
          • 1970-01-01
          相关资源
          最近更新 更多