开发者

Syntax of ruby function type in a class

开发者 https://www.devze.com 2023-04-12 09:00 出处:网络
If I have a class in Ruby: class Person def get_person end protected def check_person_1 end def check_person_2

If I have a class in Ruby:

class Person
  def get_person

  end

  protected
  def check_person_1

  end
  def check_person_2

  end

  private
  def auth_开发者_StackOverflow中文版person_1

  end
  def auth_person_2

  end

end

is auth_person_2 a private function or public or protected function? I mean I do not have the "private" keyword above the function name, but it is under the auth_person_1 function which is however directly under "private", what function type auth_person_2 is in this case? and how about function check_person_2 ?


in this case auth_person1/2 would be private, check_person1/2 would be protected and get_person would be public.

Functions look for the last keyword and that's what they use.

You can also do it this way :

class Person
def method1
end
def method2
end
def method3
end
def method4
end

public :method1, :method4
protected :method2
private :method3

end

Doing something like this would also work :

class Person
def method
end

private
def method1
end

public
def method2
end
end

You can have them in any order and use the same keyword more than once.


Ruby is not like C# where you have to define the encapsulation for each method.

Everything bellow the method "private" is private until you call one of the other methods (private, public or protected). For example, you can use "public" to define a public method after a block of private ones.

By default your class is public.

class Hello
  ...
end

is the same as

class Hello
  public
  ...
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号