----- Original Message ----- From: "Meino Christian Cramer" <mccramer / s.netic.de> To: "ruby-talk ML" <ruby-talk / ruby-lang.org>; <dblack / superlink.net> Sent: Saturday, August 16, 2003 12:31 PM Subject: Re: Newbie Q: Data encapsulation with Ruby Hi, Meino... I'll make some comments. Maybe we can make things more clear. > Yes... > But...did I understood so far: > "Setting" an attribute with "attr_accessor" means it is world > readable and writeable (or speaking the UNIX-way, it is > rw-rw-rw ;) ? First of all, understand that an instance variable is simply a variable. It starts with an @ sign and is scoped within the instance methods. The "setter" and "getter" are methods, and they are entirely optional. You define them ONLY when you want the outside world to access the variable this way. Inside your class, you can use any number of instance variables that are not accessible to the outside world at all. Also note that, in Ruby: private, public, and protected apply strictly to methods. They have nothing to do with instance variables, which are always private. I hope this does not confuse you further, but I will say this also... You understand now how the attr_* methods work, I think. But remember that this is only a shorthand. You can create methods of any name "by hand" -- and the names do NOT have to match instance variables at all. You could (though it would be silly) create methods that "look" like readers and writers, but do nothing of the sort: class C def initialize(val) @foo = val # Here's an instance var @bar = "some value" # Here's another (totally # invisible to outside world) end def foo puts "I'm a stupid method pretending to be a getter." end def foo=(x) puts "I look like a setter, but I don't even look at my parameter." end end And someone may point out that even a "hidden" instance var can be accessed by someone trying hard enough... but I don't want to mention advanced things to you yet. If you are interested, you can look at things like 'send' and 'instance_eval'. Cheers, Hal