我猜想一些 Ruby 内部结构
class MyClass
def instance_variable=(var)
puts "inside getter"
instance_variable = var
end
def function_1
self.instance_variable = "whatever"
end
def function_2
@instance_variable = "whatever"
end
end
myclass = MyClass.new
myclass.function1
控制台上的“inside getter”结果
myclass.function2
没有。
我是 Ruby 新手,不知道其中的区别,在网上找不到它......
提前致谢!
编辑:
我假设通过附加“=”,我覆盖了隐式定义的实例变量“instance_variable”的 getter 方法。
这也是我这么称呼它的原因。
我以前不允许在函数名称中使用“=”。
这就是为什么我认为它有一些特殊的意义。
感谢您的帮助。
EDIT2:
我只是认为我真的覆盖了作业,而不仅仅是吸气剂。我把这一切都搞混了。
抱歉和谢谢。
class MyClass
def instance_variable=(var)
puts "inside getter"
instance_variable = var
end
def function_1
self.instance_variable = "whatever"
end
def function_2
@instance_variable = "whatever"
end
end
myclass = MyClass.new
myclass.function1
results wiht "inside getter" on the console
myclass.function2
does not.
Im new to Ruby, do not know the difference, couldnt find it on the web...
Thanks in advance!
EDIT:
I assumed that by appending the "=", I overwrite a getter method for an implicitly defined instance variable "instance_variable."
That's also the reason why I called it that way.
Im not used to be allowed to use "=" in function names.
Thats why I assumed it would had some special meaning.
Thanks for your help.
EDIT2:
I just thought I really overwrite the assignment and not only the getter. I got it all mixed up.
Sorry and Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已(误导性地)将您的 setter 命名为
instance_variable
。它不是实例变量,而是设置实例变量的方法。当您调用 self.instance_variable= 时,您正在调用该方法。当您直接设置
@instance_variable
时,您正在设置变量本身,这就是不调用setter方法的原因。更惯用的命名约定如下:
当然,为了简单起见,您可以使用传递类型 getter 和 setter
上面的方法是语法糖,它们为您生成 get 和/或 set 方法。如果需要,可以稍后覆盖它们以提供附加功能。
编辑:我看到您已经进行了更新,只是想指出该方法根本不设置实例变量:
在这种情况下
instance_variable
只是一个局部变量,将被丢弃为该方法一退出。局部变量优先于实例方法,并且实例变量始终以@
符号开头。You have (misleading) named your setter
instance_variable
. It is not an instance variable, it is a method that sets an instance variable.When you call
self.instance_variable=
you are calling that method. When you set@instance_variable
directly you are setting the variable itself, and that is why the setter method is not called.A more idiomatic naming convention would be something like:
Of course, for simply, pass-through type getters and setters you can use
The above methods are syntactic sugar which generate the get and/or set methods for you. They can be overriden later to provide additional functionality if needed.
EDIT: I see that you have made an update and just wanted to point out that this method doesn't set an instance variable at all:
In this case
instance_variable
is simply a local variable and will be discarded as soon as the method exits. Local variables take precedence over instance methods, and instance variables always begin with a@
symbol.