为什么在 Ruby 中应该避免 @@class_variables?
我知道有人说在 Ruby 中应该避免使用类变量(例如 @@class_var
),而应该在类作用域中使用实例变量(例如 @instance_var
) :
def MyClass
@@foo = 'bar' # Should not do this.
@foo = 'bar' # Should do this.
end
为什么在 Ruby 中使用类变量不受欢迎?
I know that some say that class variables (e.g. @@class_var
) should be avoid in Ruby and should use the an instance variable (e.g. @instance_var
) in the class scope instead:
def MyClass
@@foo = 'bar' # Should not do this.
@foo = 'bar' # Should do this.
end
Why is the use of class variables frowned upon in Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类变量经常受到诟病,因为它们有时在继承方面的行为令人困惑:
如果您使用类实例变量,您会得到:
这通常更有用。
Class variables are often maligned because of their sometimes confusing behavior regarding inheritance:
If you use class instance variables instead, you get:
This is often more useful.
当心;类
@@variables
和实例@variables
不是同一件事。来自: http://sporkmonger.com /2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby
Be careful; class
@@variables
and instance@variables
are not the same thing.From: http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby