ruby高级语法

以下是 Ruby 高级语法的详细总结,涵盖元编程、模式匹配、闭包、并发模型等核心主题:


一、元编程(Metaprogramming)

1. 动态定义方法
ruby 复制代码
class DynamicClass
  # 使用 define_method 动态定义方法
  ["foo", "bar"].each do |method_name|
    define_method(method_name) do
      "Called #{method_name}"
    end
  end
end

obj = DynamicClass.new
obj.foo # => "Called foo"
2. 方法缺失(method_missing)
ruby 复制代码
class Ghost
  def method_missing(name, *args)
    "Method #{name} does not exist, args: #{args}"
  end
end

ghost = Ghost.new
ghost.unknown_method(1, 2) # => "Method unknown_method does not exist, args: [1, 2]"
3. 单例类(Singleton Class)
ruby 复制代码
str = "hello"
# 为单个对象定义方法
def str.custom_method
  self.upcase
end

str.custom_method # => "HELLO"

二、模块(Module)与混入(Mixin)

1. extend vs include
ruby 复制代码
module Tools
  def tool
    "Tool!"
  end
end

class Robot
  include Tools  # 混入为实例方法
  extend Tools   # 混入为类方法
end

Robot.new.tool # => "Tool!"
Robot.tool     # => "Tool!"
2. 钩子方法(Hook Methods)
ruby 复制代码
module Loggable
  def self.included(base)
    puts "#{base} included Loggable"
  end
end

class User
  include Loggable # 输出 "User included Loggable"
end

三、Proc 与 Lambda

1. 差异与闭包
ruby 复制代码
# Proc 不检查参数数量
p = proc { |a, b| [a, b] }
p.call(1) # => [1, nil]

# Lambda 检查参数数量
l = lambda { |a, b| [a, b] }
l.call(1) # ArgumentError

# 闭包捕获上下文
def counter
  count = 0
  -> { count += 1 }
end
c = counter
c.call # => 1
c.call # => 2
2. & 符号与块转换
ruby 复制代码
def process(&block)
  block.call
end

process { puts "Block executed" }

四、模式匹配(Ruby 3.0+)

1. case...in 语法
ruby 复制代码
case { name: "Alice", age: 30 }
in { name: "Alice", age: 18.. }
  "Adult Alice"
else
  "Unknown"
end
# => "Adult Alice"
2. 数组与哈希解构
ruby 复制代码
case [1, [2, 3]]
in [a, [b, c]]
  puts "a=#{a}, b=#{b}, c=#{c}" # a=1, b=2, c=3
end

五、并发与纤程(Fiber)

1. 纤程协作式并发
ruby 复制代码
fiber1 = Fiber.new do
  Fiber.yield "First"
  "Second"
end

fiber2 = Fiber.new do
  "Hello"
end

puts fiber1.resume # => "First"
puts fiber2.resume # => "Hello"
puts fiber1.resume # => "Second"
2. Ractor(Ruby 3.0+ 的 Actor 模型)
ruby 复制代码
# 创建并行执行的 Ractor
ractor = Ractor.new do
  Ractor.receive * 2
end

ractor.send(5) # 发送数据
ractor.take    # => 10

六、方法链与 DSL

1. 方法链优化(tap)
ruby 复制代码
[1, 2, 3].tap { |arr| arr.delete(1) }.map(&:to_s)
# => ["2", "3"]
2. 领域特定语言(DSL)
ruby 复制代码
class Configurator
  def self.setup(&block)
    config = new
    config.instance_eval(&block)
    config
  end

  def name(value)
    @name = value
  end
end

config = Configurator.setup do
  name "MyApp"
end
config.instance_variable_get(:@name) # => "MyApp"

七、高级块用法

1. 符号到 Proc 的简写
ruby 复制代码
# 等同于 { |x| x.upcase }
["a", "b"].map(&:upcase) # => ["A", "B"]
2. 自定义块参数
ruby 复制代码
def wrap_log
  puts "Start"
  yield
  puts "End"
end

wrap_log { puts "Running..." }
# 输出:
# Start
# Running...
# End

八、解构赋值与模式扩展

1. 多重赋值
ruby 复制代码
a, (b, c) = [1, [2, 3]]
a # => 1
b # => 2
c # => 3
2. 自定义解构方法
ruby 复制代码
class Point
  def deconstruct
    [x, y]
  end
end

case Point.new(3, 4)
in [a, b]
  "x=#{a}, y=#{b}" # => "x=3, y=4"
end

九、元类(MetaClass)与类扩展

ruby 复制代码
class String
  class << self
    def meta_method
      "This is a class method"
    end
  end
end

String.meta_method # => "This is a class method"

十、高级特性

1. Refinements(局部猴子补丁)
ruby 复制代码
module StringExtensions
  refine String do
    def reverse_upcase
      reverse.upcase
    end
  end
end

using StringExtensions
"hello".reverse_upcase # => "OLLEH"
2. 动态常量访问
ruby 复制代码
class Demo
  CONST = 100
end

Demo.const_get(:CONST) # => 100
3. 自定义运算符
ruby 复制代码
class Vector
  def +(other)
    # 自定义向量加法
  end
end

十一、惰性枚举(Lazy Enumerator)

ruby 复制代码
# 避免立即生成所有元素
(1..Float::INFINITY).lazy.select(&:even?).first(5) # => [2, 4, 6, 8, 10]

总结

Ruby 的高级语法特性使其成为一门高度灵活的语言,尤其擅长:

  • 元编程:动态修改类和对象行为。
  • 函数式编程:Lambda、闭包和链式调用。
  • DSL 设计:通过块和类方法构建领域特定语言。
  • 并发模型:纤程和 Ractor 支持高效并发。

建议结合实际项目(如复杂 Web 服务或脚本工具)实践这些高级特性,并参考 Ruby 官方文档 深入探索。

--- END ---

相关推荐
云边小贩36 分钟前
C++ STL学习 之 泛型编程
开发语言·c++·学习·类与对象
Lethehong38 分钟前
飞算JavaAI:革新Java开发体验的智能助手
java·开发语言·java开发·飞算javaai炫技赛
-睡到自然醒~44 分钟前
[go] 命令模式
java·开发语言·javascript·后端·golang·命令模式
多读书1931 小时前
Java多线程进阶-深入synchronized与CAS
java·开发语言·java-ee
啊阿狸不会拉杆2 小时前
《算法导论》第 24 章 - 单源最短路径
开发语言·数据结构·c++·算法·php
衍余未了2 小时前
Centos9傻瓜式linux部署CRMEB 开源商城系统(PHP)
开发语言·php
xzkyd outpaper2 小时前
Kotlin 协程启动方式
android·开发语言·kotlin
集成显卡2 小时前
在JVM跑JavaScript脚本 | 简单 FaaS 架构设计与实现
开发语言·javascript·jvm·设计模式·kotlin·软件开发·faas
数据熊猫Taobaoapi20142 小时前
JavaScript 实现模块懒加载的几种方式
开发语言·javascript·ecmascript
Linux运维技术栈3 小时前
解决程序连不上RabbitMQ:Attempting to connect to/access to vhost虚拟主机挂了的排错与恢复
分布式·rabbitmq·ruby