Ruby / IRB:将实例变量设置为私有或其他不可见?
在 Ruby 中,当我做这样的事情时:
class Foo
...
def initialize( var )
@var = var
end
...
end
然后,如果我在控制台中返回 foo ,我会得到这个对象表示:
#<Foo:0x12345678910234 @var=...........>
有时我有一个实例变量,它是一个长哈希或其他东西,它使得读取其余部分的对象要困难得多。
我的问题是:有没有办法将对象中的实例变量设置为“私有”或以其他方式不可见,以便在返回该对象时不会将其打印为对象表示的一部分控制台?
谢谢!
In Ruby, when I do something like this:
class Foo
...
def initialize( var )
@var = var
end
...
end
Then if I return a foo
in console I get this object representation:
#<Foo:0x12345678910234 @var=...........>
Sometimes I have an instance variable that is a long hash or something and it makes reading the rest of the object much more difficult.
My question is: is there a way to set an instance variable in an object to "private" or otherwise invisible so that it won't be printed as part of the object representation if that object is returned in the console?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过一番快速搜索后,我认为 Ruby 不支持私有实例变量。最好的选择是重写对象的
to_s
方法(或猴子补丁Object#to_s
),以仅输出您想要查看的实例变量。为了让事情变得更简单,您可以创建一个要隐藏的变量黑名单:请注意,仍然可以通过 obj.instance_variables 和 obj.instance_variable_get 访问它们,但在至少它们不会妨碍您的调试。
After some quick searching, I don't think Ruby supports private instance variables. Your best bet is to override your object's
to_s
method (or monkey patchObject#to_s
) to only output the instance variables you want to see. To make things easier, you could create a blacklist of variables you want to hide:Note that they will still be accessible through
obj.instance_variables
andobj.instance_variable_get
, but at the very least they won't get in the way of your debugging.