6-ruby 方法详解
基本语法格式
def 方法名(参数1, 参数2=默认值, *可变参数, &代码块)
# 方法体
返回值 # 可省略,默认返回最后一行表达式的值
end
1. 基本方法定义
无参数方法
def greet
puts "Hello, Ruby!"
end
greet # 输出: Hello, Ruby!
带参数方法
def add(a, b)
a + b # 隐式返回
end
puts add(3, 5) # 输出: 8
2. 参数类型
默认参数
# 默认参数
def say_hello(name="Ruby")
puts "Hello, #{name}!"
end
say_hello # 输出: Hello, Ruby!
say_hello("Tom") # 输出: Hello, Tom!
可变参数
# 可变参数
def sum(*numbers)
numbers.sum
end
puts sum(1, 2, 3) # 输出: 6
puts sum(4, 5, 6, 7) # 输出: 22
关键字参数
# 关键字参数
def create_person(name:, age:, gender: "unknown")
{ name: name, age: age, gender: gender }
end
p create_person(name: "Alice", age: 25)
# 输出: {:name=>"Alice", :age=>25, :gender=>"unknown"}
3. 返回值
显式返回
# 显式返回
def max(a, b)
return a if a > b
b
end
puts max(10, 20) # 输出: 20
多返回值(返回数组)
# 多返回值(返回数组)
def min_max(array)
[array.min, array.max]
end
min, max = min_max([3, 1, 4, 1, 5, 9])
puts "Min: #{min}, Max: #{max}" # 输出: Min: 1, Max: 9
4. 代码块参数
# 代码块参数
def repeat(n)
n.times { yield if block_given? }
end
repeat(3) { puts "Hi hello!" }
# 输出:
# Hi hello!
# Hi hello!
# Hi hello!
5. 方法别名
# 方法别名
def old_method
puts "This is old method"
end
alias new_method old_method
new_method # 输出: This is old method
6. 类方法
# 类方法
class Calculator
def self.add(a, b) # 类方法定义方式1
a + b
end
class << self # 类方法定义方式2
def subtract(a, b)
a - b
end
end
end
puts Calculator.add(5, 3) # 输出: 8
puts Calculator.subtract(5, 3) # 输出: 2
7. 私有方法
# 私有方法
class BankAccount
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount
log_transaction("Deposit", amount)
end
# 定义私有方法,在 private 下的都是私有方法
private
def log_transaction(type, amount)
puts "#{type}: #{amount}"
end
def log_transaction2(type, amount)
puts "#{type}: #{amount}"
end
# 定义公共方法,在 public 下的都是公共方法
public
def get_balance
p @balance
end
end
account = BankAccount.new(100)
account.deposit(50) # 输出: Deposit: 50
account.get_balance # 输出: 150
# account.log_transaction("Test", 10) # 会报错,私有方法不能直接调用
# account.log_transaction2("Test", 10) # 会报错,私有方法不能直接调用
8. 方法查询
# 方法查询
puts "方法列表: #{BankAccount.instance_methods(false)}"
puts "类方法列表: #{BankAccount.methods(false)}"
# 输出:
# 方法列表: [:deposit, :get_balance]
# 类方法列表: []
9. 方法重定义
# 方法重定义
def say_hi
puts "Hi!"
end
say_hi # 输出: Hi!
def say_hi
puts "Hello!"
end
say_hi # 输出: Hello!
10. 方法缺失处理
# 方法缺失处理
class DynamicMethods
def method_missing(name, *args)
if name.to_s.start_with?('find_by_')
puts "动态查找: #{name} 参数: #{args}"
else
super
end
end
end
dm = DynamicMethods.new
dm.find_by_name("Alice") # 输出: 动态查找: find_by_name 参数: ["Alice"]
最佳实践
- 方法名使用小写字母和下划线(snake_case)
- 方法名应清晰表达其功能
- 保持方法短小精悍(最好不超过10行)
- 避免过多参数(超过3个考虑使用哈希或关键字参数)
- 使用问号结尾命名返回布尔值的方法
- 使用感叹号结尾命名有"危险"或会修改对象的方法