简体   繁体   中英

Do Ruby instance variables have access modifiers?

So what I learned is that when I call a variable on an object eg

my_object.variable

A method called variable is returning the value of variable

def variable
   @variable
end

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

First, there is a bit of terminology to clean up in the question before answering it.

One is that you never "call" variables. The Ruby expression

my_object.variable

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 . :)

The second is if you did define the method like this

def variable
   @variable
end

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 only be referenced within an object's methods, and never with a prefix! In other words, you can never write this:

obj.@var

That's just a syntax error. You can write

obj.var

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

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!

There are several ways to make a method private in Ruby.

Use private to make all later methods private:

class Foo
  def public_method
  end

private

  def private_method
  end
end

Or make a method private after you defined it:

class Foo
  def public_method
  end

  private :public_method # public_method is now private
end

Or - since the method definition returns a symbol too - this also works:

class Foo
  private def method_name
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM