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: ruby
January 29th, 2007 at 7:14 pm
Very nice trick when exploring code in the ruby debuggers
January 29th, 2007 at 7:14 pm
Also:
user.instance_variable_get(“@password”)
January 29th, 2007 at 7:14 pm
Agree – that exposes intent a little better than an instance eval. All other things being equal – that might be a better option.