可見性¶
方法預設為公開:編譯器總是允許您調用它們。因此沒有 public
關鍵字。
方法可以被標記為 private
或 protected
。
私有方法¶
private
方法只能在沒有接收器的情況下調用,也就是說,在點之前沒有任何東西。唯一的例外是使用 self
作為接收器。
class Person
private def say(message)
puts message
end
def say_hello
say "hello" # OK, no receiver
self.say "hello" # OK, self is a receiver, but it's allowed.
other = Person.new
other.say "hello" # Error, other is a receiver
end
end
請注意,子類別可見 private
方法。
class Employee < Person
def say_bye
say "bye" # OK
end
end
私有型別¶
私有型別只能在定義它們的命名空間內被引用,且永遠不能使用完整名稱。
class Foo
private class Bar
end
Bar # OK
Foo::Bar # Error
end
Foo::Bar # Error
private
可以與 class
、module
、lib
、enum
、alias
和常數一起使用。
class Foo
private ONE = 1
ONE # => 1
end
Foo::ONE # Error
受保護方法¶
protected
方法只能在以下情況下調用:
- 與當前型別相同型別的實例
- 與當前型別相同命名空間(類別、結構、模組等)的實例
# Example of 1
class Person
protected def say(message)
puts message
end
def say_hello
say "hello" # OK, implicit self is a Person
self.say "hello" # OK, self is a Person
other = Person.new "Other"
other.say "hello" # OK, other is a Person
end
end
class Animal
def make_a_person_talk
person = Person.new
person.say "hello" # Error: person is a Person but current type is an Animal
end
end
one_more = Person.new "One more"
one_more.say "hello" # Error: one_more is a Person but current type is the Program
# Example of 2
module Namespace
class Foo
protected def foo
puts "Hello"
end
end
class Bar
def bar
# Works, because Foo and Bar are under Namespace
Foo.new.foo
end
end
end
Namespace::Bar.new.bar
protected
方法只能從其類別或其後代的範圍內調用。這包括類別範圍以及定義受保護方法的相同型別的類別方法和實例方法的主體,以及包含或繼承該型別的所有型別以及該命名空間中的所有型別。
class Parent
protected def self.protected_method
end
Parent.protected_method # OK
def instance_method
Parent.protected_method # OK
end
def self.class_method
Parent.protected_method # OK
end
end
class Child < Parent
Parent.protected_method # OK
def instance_method
Parent.protected_method # OK
end
def self.class_method
Parent.protected_method # OK
end
end
class Parent::Sub
Parent.protected_method # OK
def instance_method
Parent.protected_method # OK
end
def self.class_method
Parent.protected_method # OK
end
end
私有頂層方法¶
private
頂層方法僅在當前檔案中可見。
one.cr
private def greet
puts "Hello"
end
greet # => "Hello"
two.cr
require "./one"
greet # undefined local variable or method 'greet'
這允許您在檔案中定義僅在該檔案中已知的輔助方法。
私有頂層型別¶
private
頂層型別僅在當前檔案中可見。
one.cr
private class Greeter
def self.greet
"Hello"
end
end
Greeter.greet # => "Hello"
two.cr
require "./one"
Greeter.greet # undefined constant 'Greeter'