Ruby赋值运算符 #

一、赋值运算符概述 #

Ruby提供了多种赋值方式,包括基本赋值、复合赋值和并行赋值。

运算符 描述 示例
= 赋值 a = 1
+= 加赋值 a += 1
-= 减赋值 a -= 1
*= 乘赋值 a *= 2
/= 除赋值 a /= 2
%= 取余赋值 a %= 3
**= 幂赋值 a **= 2
=
&&= 与赋值 a &&= 2

二、基本赋值 #

2.1 简单赋值 #

ruby
a = 1
name = "Ruby"
arr = [1, 2, 3]
hash = { a: 1, b: 2 }

2.2 链式赋值 #

ruby
a = b = c = 0
a
b
c

2.3 方法返回值赋值 #

ruby
def get_value
  42
end

result = get_value
result

三、复合赋值 #

3.1 算术复合赋值 #

ruby
a = 10

a += 5
a -= 3
a *= 2
a /= 4
a %= 3
a **= 2

3.2 展开形式 #

ruby
a = 10

a += 5
a = a + 5

a *= 2
a = a * 2

3.3 字符串复合赋值 #

ruby
s = "Hello"
s += " World"
s << "!"

s *= 2

3.4 数组复合赋值 #

ruby
arr = [1, 2]
arr += [3, 4]
arr -= [2]

四、或赋值(||=) #

4.1 基本用法 #

ruby
a = nil
a ||= 1
a

a ||= 2
a

4.2 工作原理 #

ruby
a ||= b

a = a || b

a || a = b

4.3 应用场景 #

ruby
def get_name
  @name ||= "Default"
end

def cache
  @cache ||= {}
end

def settings
  @settings ||= load_settings
end

def load_settings
  puts "Loading..."
  { timeout: 30, retry: 3 }
end

settings
settings

4.4 注意事项 #

ruby
a = false
a ||= true
a

a = 0
a ||= 1
a

a = ""
a ||= "default"
a

五、与赋值(&&=) #

5.1 基本用法 #

ruby
a = 10
a &&= 20
a

a = nil
a &&= 20
a

5.2 工作原理 #

ruby
a &&= b

a = a && b

a && a = b

5.3 应用场景 #

ruby
def update_if_exists(hash, key, value)
  hash[key] &&= value
end

hash = { a: 1, b: 2 }
update_if_exists(hash, :a, 10)
update_if_exists(hash, :c, 30)
hash

六、并行赋值 #

6.1 基本用法 #

ruby
a, b = 1, 2
a
b

a, b, c = 1, 2, 3
a
b
c

6.2 交换变量 #

ruby
a, b = 1, 2
a, b = b, a
a
b

6.3 数组解构 #

ruby
arr = [1, 2, 3]
a, b, c = arr
a
b
c

a, *rest = [1, 2, 3, 4, 5]
a
rest

first, *, last = [1, 2, 3, 4, 5]
first
last

6.4 嵌套解构 #

ruby
a, (b, c) = [1, [2, 3]]
a
b
c

6.5 方法返回多值 #

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

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

七、属性赋值 #

7.1 实例变量赋值 #

ruby
class Person
  attr_writer :name, :age

  def initialize
    @name = "Unknown"
    @age = 0
  end
end

person = Person.new
person.name = "Ruby"
person.age = 30

7.2 哈希键赋值 #

ruby
hash = {}
hash[:a] = 1
hash[:b] = 2
hash.store(:c, 3)
hash

7.3 数组元素赋值 #

ruby
arr = [1, 2, 3]
arr[0] = 10
arr[1, 2] = [20, 30]
arr

八、条件赋值 #

8.1 三元运算符赋值 #

ruby
age = 20
status = age >= 18 ? "成年" : "未成年"
status

8.2 条件语句赋值 #

ruby
def get_status(score)
  if score >= 90
    "优秀"
  elsif score >= 60
    "及格"
  else
    "不及格"
  end
end

result = get_status(85)
result

8.3 case语句赋值 #

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

grade = get_grade(85)
grade

九、块赋值 #

9.1 块参数解构 #

ruby
[[1, 2], [3, 4]].each do |a, b|
  puts "#{a}, #{b}"
end

{ a: 1, b: 2 }.each do |key, value|
  puts "#{key}: #{value}"
end

9.2 方法参数解构 #

ruby
def process((a, b))
  puts "a: #{a}, b: #{b}"
end

process([1, 2])
process([3, 4, 5])

十、实用示例 #

10.1 配置默认值 #

ruby
class Config
  attr_accessor :host, :port, :timeout

  def initialize(options = {})
    @host = options[:host] || "localhost"
    @port = options[:port] || 3000
    @timeout = options[:timeout] || 30
  end
end

config = Config.new(host: "example.com")
config.host
config.port

10.2 懒加载 #

ruby
class LazyLoader
  def data
    @data ||= load_data
  end

  private

  def load_data
    puts "Loading data..."
    (1..100).to_a
  end
end

loader = LazyLoader.new
loader.data
loader.data

10.3 参数解构 #

ruby
def parse_point(point)
  x, y = point
  puts "Point(#{x}, #{y})"
end

parse_point([10, 20])

def parse_user(user_data)
  name, age, *rest = user_data
  puts "Name: #{name}, Age: #{age}"
end

parse_user(["Ruby", 30, "Beijing", "Developer"])

10.4 交换数组元素 #

ruby
def swap(arr, i, j)
  arr[i], arr[j] = arr[j], arr[i]
end

arr = [1, 2, 3, 4, 5]
swap(arr, 0, 4)
arr

10.5 批量赋值 #

ruby
def assign_attributes(obj, attributes)
  attributes.each do |key, value|
    obj.send("#{key}=", value) if obj.respond_to?("#{key}=")
  end
end

class User
  attr_accessor :name, :email, :age
end

user = User.new
assign_attributes(user, { name: "Ruby", email: "ruby@example.com", age: 30 })
user.name
user.email

十一、最佳实践 #

11.1 使用||=设置默认值 #

ruby
def settings
  @settings ||= {}
end

def name
  @name ||= "Default"
end

11.2 使用并行赋值交换变量 #

ruby
a, b = b, a

11.3 避免链式赋值混淆 #

ruby
a = b = c = []
a << 1
b
c

a = []
b = []
c = []

11.4 使用解构简化代码 #

ruby
result, error = perform_operation

if error
  handle_error(error)
else
  process_result(result)
end

十二、总结 #

本章我们学习了:

  1. 基本赋值:=、链式赋值
  2. 复合赋值:+=、-=、*=、/=等
  3. 或赋值:||=、懒加载、默认值
  4. 与赋值:&&=、条件更新
  5. 并行赋值:多变量赋值、交换、解构
  6. 属性赋值:实例变量、哈希、数组

接下来让我们学习Ruby的运算符优先级!

最后更新:2026-03-27