Setter 不适用于 -=、+= 等? [英] Setter doesn't work with -=, +=, etc?

查看:41
本文介绍了Setter 不适用于 -=、+= 等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我会收到 nil 错误.我正确地创建了二传手.但它不接受 -=、+= 或 = 运算符后面的自身.为什么?

I don't understand why I get a nil error. I created the setter properly. But it does not accept -=, +=, or itself behind the = operator. Why?

class Test
  def var; @var || 0; end
  def var=(value)
    @var = value
  end

  def initialize
    @var = 2.4 # Sample value
  end

  def test
    puts var
    var -= 1 # <<< crash: undefined method for nil class
    puts var
    var = var - 1 # <<< crash: undefined method for nil class
    puts var
  end
end

a = Test.new
a.test

推荐答案

Write as

def test
    puts var
    self.var -= 1
    puts var
    self.var = var - 1
    puts var
end

如果您不使用 self,那么 Ruby 会将那些 var 视为局部变量,而不是 setter 方法调用.

If you don't use self, then Ruby will treat those var as a local variables, rather then setter method calls.

请记住,在 Ruby 中,方法调用永远不会在没有接收器的情况下进行(隐式/显式).现在,如果您编写 var = 1,Ruby 将视为 局部变量赋值.但是,如果您编写 self.var,Ruby 会将其解析为方法调用,并尝试调用您的 setter 方法(如果您已定义).还要记住 self.var = 1self.var=(1)语法糖.

Just remember, in Ruby method call can never be made without receiver(implicit/explicit). Now if you write var = 1, Ruby will treat as local variable assignment. But if you write self.var, Ruby will parse it as a method call, and will try to call your setter method, if you defined. Also remember self.var = 1 is a syntactic sugar of self.var=(1).

关于相同的还有更多有趣的讨论,值得一读 私有 setter 可以被自己调用,为什么不是吸气剂?

There is more interesting discussion about the same, worth to read Private setters can be called by self, why not getters?

最近发现了一个关于私有设置器错误.这是 Bug 票,现在也已修复.

There is a recent bug was found regarding the private setters. Here is the Bug ticket, and it is now fixed too.

这篇关于Setter 不适用于 -=、+= 等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆