局部变量、实例变量、全局变量和类变量有什么区别?
我刚刚学习 Ruby,并且有一个非常初学者的问题。这四种类型变量之间的区别主要只是作用域。那么局部变量只能在当前块中使用,实例变量只能在当前实例中使用,全局变量只能在每个范围内使用,最后,类变量只能在当前类中使用吗?多谢!
I'm just learning Ruby and have and have an extremely beginner question. Is the difference between the four types of variables mainly just scope. So local variables can only be used within the current block, instance variables within the current instance, global variables within every scope and finally, class variables within the current class? Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你说得对,尽管有一些
皱纹。类变量 (@@foo) 可以从类方法和类的实例方法访问。
它们在继承方面的行为有些不直观:如果您在基类中设置这样的变量并在子类中再次设置它,那么您将更改层次结构中所有类的值。如果您使用类变量来存储设置,这通常不是您想要的 - 您希望子类能够“覆盖”基类中的值,而不实际更改基类的值。 Rails为此提供了
class_attribute
:它创建具有该行为的访问器方法。最后,并不是真正的单独类型,但由于类是对象,因此也有类实例变量。它们对继承没有任何作用——层次结构中的每个类对象都有自己完全独立的对象。与类变量不同,实例不能直接操作类实例变量。
You've got it right although there are some
wrinkles. Class variables (@@foo) can be accessed both from the class methods and the instance methods of a class.
They behave somewhat unintuitively with respect to inheritance: if you set such a variable in a base class and set it again in the subclass then you will change the value for all classes in the hierarchy. If you're using class variables to store settings this is often not what you want - you want subclasses to be able to "override" values from the base class without actually changing them for the base class. Rails provides
class_attribute
for this: it creates accessor methods which have that behaviour.Finally, not really a separate type, but since classes are objects there are also class instance variables. These don't do anything with respect to inheritance - each class object in a hierarchy has its own completely independant ones. Unlike class variables, instances can't directly manipulate class instance variables.
你说对了。区别只是范围而已。
You got it right. The difference is just the scope.
很高兴您能够直观地弄清楚这一点。区别只是范围(但是它们在内存中处理的方式非常不同)。
Glad you were able to figure this out intuitively. The difference is just scope (however the way they are dealt with in memory is pretty different).