What does an attr_accessor mean?

Most of the above answers use code. There is no point me repeating what they say, so I’ll try to explain the concept without code:

Explanation

• Outside parties cannot access internal CIA secrets Let’s imagine a really secret place. An agency. Let’s call this agency the CIA. Nobody knows what’s happening in the CIA apart from the people inside the CIA. In other words, external people cannot access any information in the CIA. But because it’s no good having an organisation that is completely secret, certain information is made available to the outside world - only things that the CIA wants everyone to know about of course: e.g. the Director of the CIA, how environmentally friendly this department is compared to all other government departments etc. Other information: e.g. who are its covert operatives in Iraq or Afghanistan - these types of things will probably remain a secret for the next 150 years.

• You can only access information which the CIA makes available to the public (if you’re Joe Bloggs off the street). Or to use CIA parlance you can only access information that is “cleared”. The information that the CIA wants to make available to the general public outside the CIA are called: attributes.

The meaning of read and write attributes:

• In the case of the CIA, most attributes are “read only”. This means you can ask: “who is the director of the CIA?” and you will get a straight answer. But what you cannot do with “read only” attributes is make changes changes in the CIA. e.g. you cannot making a phone call and suddenly decide that you want Kim Kardashian to be the Director, or that you want Paris Hilton to be the Commander in Chief. Imagine all CIA information is noted down on a piece of paper. Basically you cannot add/subtract/edit or write anything on that paper if you don’t have “write” access. If read access was the only thing you had, well tough pities.

• If the attributes gave you “write” access, then you could do that. In other words accessors allow you to make inquiries, or to make changes, to organisations that otherwise do not let external people in.

• Objects inside a class can easily access each other

On the other hand, if you were already inside the CIA, then you could easily call up your CIA operative in Kabul and ask him if he wants to have a beer with the local Kabul guy after work. But if you’re outside the CIA, you simply will not be given access: you will not be able to know who they are (read access), and you will not be able to change their mission (write access).

Exact same thing with classes and your ability to access variables, properties and methods within them.

I hope that helps!

Written on December 12, 2016