Ruby 公共方法
最后修改日期:2025 年 4 月 27 日
本教程解释了如何使用 Ruby 的 public
方法。公共方法构成了类的接口,并且可以从任何地方访问。
Ruby 中的 public 关键字定义了可以在程序中任何位置调用的方法。默认情况下,Ruby 中的所有方法都是公共的,除非明确标记为其他类型。
公共方法代表类的外部接口。它们应该是稳定且文档完善的,因为其他代码依赖于它们。
基本公共方法示例
这个简单的例子演示了 Ruby 类中的基本公共方法。公共方法可以在类的实例上调用。
class Greeter def say_hello puts "Hello, world!" end end greeter = Greeter.new greeter.say_hello
say_hello
方法默认是公共的。我们可以在任何 Greeter
实例上调用它。公共方法构成了类的公共 API。
显式公共声明
Ruby 允许使用 public
关键字显式将方法声明为公共。这在定义私有或保护方法之后很有用。
class Calculator def add(a, b) a + b end private def secret_method puts "This is private" end public def multiply(a, b) a * b end end calc = Calculator.new puts calc.add(2, 3) puts calc.multiply(2, 3)
multiply
方法在私有部分之后显式设为公共。add
和 multiply
都可以访问。
公共类方法
类方法也可以是公共的。这些方法是在类本身而不是实例上调用的。self.
前缀定义了类方法。
class Logger def self.log(message) puts "[LOG] #{message}" end def self.public_log(message) puts "[PUBLIC] #{message}" end private_class_method :log end Logger.public_log("System started")
只有 public_log
在此处可访问。我们使用 private_class_method
将 log
设为私有。公共类方法通常用于实用函数。
模块中的公共方法
模块可以定义公共方法,这些方法将提供给包含它们的类。这些方法成为包含类公共接口的一部分。
module Printable def print_info puts "Information: #{info}" end private def info "Sample data" end end class Document include Printable end doc = Document.new doc.print_info
print_info
方法是公共的,可在 Document
实例上使用。私有方法 info
仅在模块内部可访问。
公共访问器方法
Ruby 为创建公共的 getter 和 setter 方法提供了快捷方式。这些通常用于公开实例变量。
class Person attr_reader :name attr_writer :age attr_accessor :occupation def initialize(name, age) @name = name @age = age end def display puts "#{@name}, #{@age}, #{@occupation}" end end person = Person.new("John", 30) person.occupation = "Developer" puts person.name person.display
attr_reader
创建一个公共 getter,attr_writer
创建一个公共 setter,而 attr_accessor
则同时创建两者。这些都是公共方法。
公共方法覆盖
公共方法可以在子类中被覆盖。这允许在保持相同接口的同时修改或扩展行为。
class Animal def speak puts "Animal sound" end end class Dog < Animal def speak puts "Woof!" end end class Cat < Animal def speak super puts "Meow!" end end Dog.new.speak Cat.new.speak
Dog
和 Cat
都覆盖了公共方法 speak
。Cat
使用 super
调用父类实现。
公共方法别名
Ruby 允许为公共方法创建别名。当您想为方法提供备用名称时,这很有用。
class StringFormatter def format_text(text) text.upcase end alias :upcase_text :format_text alias_method :uc_text, :format_text end formatter = StringFormatter.new puts formatter.format_text("hello") puts formatter.upcase_text("world") puts formatter.uc_text("ruby")
alias
和 alias_method
都会为公共方法创建新名称。所有别名都保持公共,可以互换调用。
来源
本教程通过实际示例介绍了 Ruby 的公共方法,展示了声明、访问控制和常见用法模式。
作者
列出 所有 Ruby 教程。