开发者

Ruby / IRB: set instance variable to private or otherwise invisible?

开发者 https://www.devze.com 2023-03-21 08:45 出处:网络
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:

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开发者_JAVA百科 object representation if that object is returned in the console?

Thanks!


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 patch Object#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:

class Foo
  BLACK_LIST = [ :@private ]

  def initialize(public, private)
    @public = public
    @private = private
  end

  def to_s
    public_vars = self.instance_variables.reject { |var|
      BLACK_LIST.include? var
    }.map { |var|
      "#{var}=\"#{instance_variable_get(var)}\""
    }.join(" ")

    "<##{self.class}:#{self.object_id.to_s(8)} #{public_vars}>"
  end
end

Note that they will still be accessible through obj.instance_variables and obj.instance_variable_get, but at the very least they won't get in the way of your debugging.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号