Accessing Private Data in Ruby

January 29th, 2007

Of course that’s how you do it…


user.instance_eval("@password")

Every now and then you really do need to access a private variable and don’t particularly want to change the class. Especially in test code. Maybe it’s a smell, but I’d resorted to reopening classes and adding attr_accessor’s.

Moral issues aside, this is definitely a more elegant way of doing it.

3 Responses to “Accessing Private Data in Ruby”

  1. Dan Manges Says:
    Also: user.instance_variable_get("@password")
  2. Badrinath Janakiraman Says:
    Agree - that exposes intent a little better than an instance eval. All other things being equal - that might be a better option.
  3. Dustin Tinney Says:
    Very nice trick when exploring code in the ruby debuggers

Leave a Reply