Ruby返回值 #

一、返回值概述 #

Ruby方法总是返回一个值,可以是显式使用return,也可以是隐式返回最后一个表达式的值。

二、隐式返回 #

2.1 基本用法 #

ruby
def add(a, b)
  a + b
end

add(1, 2)

2.2 最后一个表达式 #

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

greet("Ruby")

2.3 条件返回 #

ruby
def check(n)
  if n > 0
    "positive"
  else
    "non-positive"
  end
end

check(5)
check(-1)

2.4 case返回 #

ruby
def grade(score)
  case score
  when 90..100 then "A"
  when 80...90 then "B"
  when 70...80 then "C"
  else "F"
  end
end

grade(85)

三、显式return #

3.1 基本用法 #

ruby
def add(a, b)
  return a + b
end

add(1, 2)

3.2 提前返回 #

ruby
def divide(a, b)
  return "Cannot divide by zero" if b == 0
  a / b.to_f
end

divide(10, 2)
divide(10, 0)

3.3 条件返回 #

ruby
def process(data)
  return nil if data.nil?
  return [] if data.empty?

  data.map(&:upcase)
end

process(nil)
process([])
process(["a", "b"])

3.4 多个return #

ruby
def find_user(id)
  return nil if id.nil?
  return nil if id <= 0

  users.find { |u| u.id == id }
end

四、多返回值 #

4.1 返回数组 #

ruby
def min_max(arr)
  [arr.min, arr.max]
end

result = min_max([3, 1, 4, 1, 5, 9])
result

min, max = min_max([3, 1, 4, 1, 5, 9])
min
max

4.2 返回哈希 #

ruby
def user_info(user)
  {
    name: user.name,
    email: user.email,
    age: user.age
  }
end

info = user_info(user)
info[:name]

4.3 解构返回 #

ruby
def parse_date(date_str)
  year, month, day = date_str.split("-").map(&:to_i)
  [year, month, day]
end

year, month, day = parse_date("2024-03-27")
year
month
day

4.4 结果与错误 #

ruby
def divide(a, b)
  return [nil, "Division by zero"] if b == 0
  [a / b.to_f, nil]
end

result, error = divide(10, 2)
result
error

result, error = divide(10, 0)
result
error

五、return在块中 #

5.1 在each中 #

ruby
def find_first(items, condition)
  items.each do |item|
    return item if condition.call(item)
  end
  nil
end

find_first([1, 2, 3, 4, 5], ->(n) { n > 3 })

5.2 在lambda中 #

ruby
my_lambda = -> { return "lambda返回" }

def test_lambda
  my_lambda = -> { return "lambda返回" }
  result = my_lambda.call
  "方法继续: #{result}"
end

test_lambda

5.3 在proc中 #

ruby
my_proc = Proc.new { return "proc返回" }

def test_proc
  my_proc = Proc.new { return "proc返回" }
  my_proc.call
  "这行不会执行"
end

test_proc

5.4 lambda vs proc #

ruby
def test_lambda
  -> { return "lambda" }.call
  "方法继续"
end

def test_proc
  Proc.new { return "proc" }.call
  "这行不会执行"
end

test_lambda
test_proc

六、链式返回 #

6.1 方法链 #

ruby
class Calculator
  def initialize(value = 0)
    @value = value
  end

  def add(n)
    @value += n
    self
  end

  def subtract(n)
    @value -= n
    self
  end

  def multiply(n)
    @value *= n
    self
  end

  def result
    @value
  end
end

calc = Calculator.new(10)
  .add(5)
  .subtract(3)
  .multiply(2)
  .result

6.2 条件链 #

ruby
def process(data)
  data
    &.fetch(:items, [])
    &.map(&:upcase)
    &.select { |s| s.length > 3 }
    &.sort
end

process({ items: ["a", "ab", "abc", "abcd"] })
process(nil)

七、实用示例 #

7.1 安全操作 #

ruby
def safe_divide(a, b)
  return [nil, "除数不能为零"] if b.zero?

  [a.to_f / b, nil]
end

result, error = safe_divide(10, 2)
result, error = safe_divide(10, 0)

7.2 查找与默认 #

ruby
def find_or_create(id)
  item = find(id)
  return item if item

  create_default(id)
end

def find_or_default(id, default = nil)
  find(id) || default
end

7.3 验证器 #

ruby
def validate_user(user)
  return [false, "用户名不能为空"] if user.name.empty?
  return [false, "邮箱格式无效"] unless valid_email?(user.email)
  return [false, "密码太短"] if user.password.length < 8

  [true, nil]
end

valid, error = validate_user(user)

7.4 状态机 #

ruby
class Order
  STATES = %i[pending processing shipped delivered cancelled].freeze

  def next_state
    current_index = STATES.index(@state)
    return nil if current_index.nil? || current_index >= STATES.length - 2

    @state = STATES[current_index + 1]
  end

  def cancel
    return false unless can_cancel?
    @state = :cancelled
    true
  end
end

八、最佳实践 #

8.1 使用隐式返回 #

ruby
def add(a, b)
  a + b
end

def add(a, b)
  return a + b
end

8.2 提前返回 #

ruby
def process(data)
  return nil if data.nil?
  return [] if data.empty?

  transform(data)
end

def process(data)
  if data.nil?
    nil
  elsif data.empty?
    []
  else
    transform(data)
  end
end

8.3 一致性 #

ruby
def find(id)
  return nil if id.nil?
  items.find { |i| i.id == id }
end

def all
  items
end

def first
  items.first
end

九、总结 #

本章我们学习了:

  1. 隐式返回:最后一个表达式的值
  2. 显式return:提前返回
  3. 多返回值:数组、哈希、解构
  4. return在块中:lambda vs proc
  5. 链式返回:方法链、条件链

接下来让我们学习Ruby的块与Proc!

最后更新:2026-03-27