Z
ZHANK
编程在线教程Ruby 教程方法定义与参数
方法与块

方法定义与参数

def 定义、默认参数/关键字参数/splat *、隐式返回、? ! 后缀约定

方法定义与参数

Ruby 方法用 def 定义,最后一行自动返回。参数支持默认值、关键字、splat 展开。

学完本章你将: 掌握 def 定义、默认/关键字/splat 参数、? ! 后缀约定。


基本定义

ruby
def greet(name)
    "Hello, #{name}!"   # 隐式返回
end

puts greet("Ruby")  # Hello, Ruby!

# 括号可省略
puts greet "Ruby"

参数类型

ruby
# 默认参数
def greet(name, greeting = "Hello")
    "#{greeting}, #{name}!"
end

# 关键字参数(推荐——自文档化)
def create_user(name:, age:, role: "user")
    { name: name, age: age, role: role }
end
create_user(name: "小明", age: 25)  # 顺序任意

# splat * —— 收集剩余参数
def sum(*nums)
    nums.reduce(:+)
end
sum(1, 2, 3, 4, 5)  # 15

# 双 splat ** —— 收集关键字参数
def config(**options)
    options
end
config(host: "localhost", port: 8080)

? 与 ! 后缀约定

ruby
# ? —— 返回布尔值
"".empty?      # true
[].include?(1) # false

# ! —— 危险版本(修改原对象)
s = "hello"
s.upcase       # 返回新字符串——s 不变
s.upcase!      # 修改 s 本身——s = "HELLO"