the_prole the_prole - 1 year ago 85
Ruby Question

Do Ruby instance variables have access modifiers?

So what I learned is that when I call a variable on an object e.g.


A method called
is returning the value of

def variable

In Java, there are access modifiers. How can Ruby make use of access modifiers if getter methods are named after their variables?

Answer Source

First, there are a few claims that need to be cleaned up in that question before answering it.

First you never "call" variables. The Ruby expression


is a method call. There is no such thing as a variable call. You call methods, not variables. Even if the method is named variable. :)

Secondly, if you did define the method like this

def variable

either directly or by saying

attr_reader :variable

Then you have a method named variable and a variable named @variable.

Now to answer the question.

Ruby places access modifiers public, protected, and private on methods only, and not on variables. Access controls on variables don't really make sense, because they cannot be seen outside of the class. In other words, you can never write anything like this


That's just a syntax error. You can write


where var is the name of a method. And the access controls apply to that method only.

So TL;DR: No, because variables can't be seen outside the class anyway. Only methods can.

The fact that you may be making variables and methods with the same name (except for the @) actually doesn't matter. Only methods have access controls.

Hope that helps clear up some understandable confusion!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download