Accessing Private Data in Ruby

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.

Tags:

3 Responses to “Accessing Private Data in Ruby”

  1. Dustin Tinney Says:

    Very nice trick when exploring code in the ruby debuggers

  2. Dan Manges Says:

    Also:

    user.instance_variable_get(“@password”)

  3. 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.