Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 470
Andrew Avatar asked May 18 '26 23:05

Andrew


1 Answers

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.

like image 89
Martin Gordon Avatar answered May 20 '26 13:05

Martin Gordon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!