3

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!

Andrew
  • 42,517
  • 51
  • 181
  • 281

1 Answers1

4

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.

Martin Gordon
  • 36,329
  • 7
  • 58
  • 54
  • That makes perfect sense, overriding `to_s` would be a very simple fix for what I'm working on. I guess it never really occurred to me that console output for returned objects was just taken from the `to_s` method! – Andrew Jul 18 '11 at 20:54