如何在Ruby中将实例变量设为私有? [英] How to make instance variables private in Ruby?

查看:87
本文介绍了如何在Ruby中将实例变量设为私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在ruby中使实例变量私有"(C ++或Java定义)?换句话说,我想要以下代码导致错误.

Is there any way to make instance variables "private"(C++ or Java definition) in ruby? In other words I want following code to result in an error.

class Base
  def initialize()
    @x = 10
  end
end

class Derived < Base
  def x
    @x = 20
  end
end

d = Derived.new

推荐答案

就像Ruby中的大多数事情一样,实例变量并不是真正的私有"变量,任何使用d.instance_variable_get :@x的人都可以访问.

Like most things in Ruby, instance variables aren't truly "private" and can be accessed by anyone with d.instance_variable_get :@x.

但是,与Java/C ++不同,Ruby中的实例变量总是 私有的.它们永远不会像方法那样成为公共API的一部分,因为只能使用该详细的getter来访问它们.因此,如果您的API有任何理智,则不必担心有人在滥用您的实例变量,因为他们会改用这些方法. (当然,如果有人想疯狂访问私有方法或实例变量,则没有办法阻止它们.)

Unlike in Java/C++, though, instance variables in Ruby are always private. They are never part of the public API like methods are, since they can only be accessed with that verbose getter. So if there's any sanity in your API, you don't have to worry about someone abusing your instance variables, since they'll be using the methods instead. (Of course, if someone wants to go wild and access private methods or instance variables, there isn’t a way to stop them.)

唯一要担心的是,某人偶然在扩展您的类时会覆盖实例变量.可以通过使用不太可能的名称来避免这种情况,例如在您的示例中将其命名为@base_x.

The only concern is if someone accidentally overwrites an instance variable when they extend your class. That can be avoided by using unlikely names, perhaps calling it @base_x in your example.

这篇关于如何在Ruby中将实例变量设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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