实现思路
- 解析模式匹配规则:将模式匹配规则解析成可操作的数据结构,例如,对于哈希表模式,将键值对解析出来,对于数组模式,明确每个位置的预期类型或值。
- 动态生成代码:使用Ruby的元编程能力,根据解析后的模式匹配规则动态生成用于匹配的代码。这可以通过
Module#define_method
等方式来实现。
- 性能优化:在生成代码时,尽量减少不必要的计算和循环。例如,对于哈希表,优先检查键是否存在,对于数组,提前确定长度是否匹配等。
Ruby 代码
class PatternMatcher
def self.match(data, pattern)
match_method = generate_match_method(pattern)
data.instance_exec(&match_method)
end
private
def self.generate_match_method(pattern)
case pattern
when Hash
generate_hash_match_method(pattern)
when Array
generate_array_match_method(pattern)
else
->(data) { data == pattern }
end
end
def self.generate_hash_match_method(pattern)
keys = pattern.keys
required_keys = keys.select { |k| pattern[k] != nil }
optional_keys = keys - required_keys
->(data) do
return false unless data.is_a?(Hash)
required_keys.all? { |k| data.key?(k) && data[k].instance_exec(&generate_match_method(pattern[k])) } &&
optional_keys.all? { |k| data.key?(k) == false || data[k].instance_exec(&generate_match_method(pattern[k])) }
end
end
def self.generate_array_match_method(pattern)
->(data) do
return false unless data.is_a?(Array) && data.length == pattern.length
pattern.each_with_index.all? do |sub_pattern, index|
data[index].instance_exec(&generate_match_method(sub_pattern))
end
end
end
end
# 使用示例
data = { name: 'John', age: 30 }
pattern = { name: String, age: Integer }
puts PatternMatcher.match(data, pattern) # 输出 true