thus IS IT IMPOSSIBLE TO DECLARE ACCESS
MODIFIERS FOR VARIABLES ?
Yes, it’s impossible. But you don’t need it. Instance variables are
always
private. You can’t do:
an_object.@var
(you’ll get a SyntaxError exception if you try that)
So, if you want to access an object’s instance variable from outside the
object, you need to provide a method which does that (note that all
attr_reader do is to define a method which returns the instance
variable).
After defining the method, you can make it protected or private, if you
need
to.
In the class above, I can declare variable genre to be protected,
and which in fact are “methods”, thus IS IT IMPOSSIBLE TO DECLARE ACCESS
MODIFIERS FOR VARIABLES ?
Can Anyone Clarify??
Thanks
Raja
What you have to do is:
class Person
you can define
public
, but stuff is public by default when it hasn’t been specified yet.
Never mind, I misunderstood the question… I thought you declared the
method
as parameter of protected, but you use it to set the visibility of an
already
existing method… Answering questions when you’re just awake doesn’t
work…
and which in fact are “methods”, thus IS IT IMPOSSIBLE TO DECLARE ACCESS
MODIFIERS FOR VARIABLES ?
In a word, no.
Short answer: Access modifiers only apply to methods. Instance
variables can only be accessed through methods, and cannot be accessed
without methods. Hence, the concept of visibility does not exist for
instance variables in ruby.
Long answer:
Although they are very similar concepts, please remember that there is
a distinction between instance variables and an attributes. Although
they can refer to the same “thing”, instance variables are the objects
internal state, whereas attributes are (effectively) the subset of the
instance variables which are exposed to the outside world.
If you are accustomed to languages where you can access the attributes
of an object without methods (such as in Java), it can be a little
confusing. In ruby, you have to use a method to access internal state.
All instance variables are accessed via accessor methods, which
conveniently have the same name as the variable. As a result, you
cannot declare access modifiers for instance variables because the
concept of visibility (private, protected, public) only exists for
methods, and not instance variables.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.