MST

星途 面试题库

面试题:Ruby模式匹配的元编程与性能优化

编写一个Ruby方法,该方法接受一个复杂的数据结构(可以是嵌套的数组、哈希表等)和一个模式匹配规则。方法内部使用元编程技术动态生成基于模式匹配的代码,并优化性能,以高效地判断数据结构是否符合给定的模式匹配规则。请详细解释你的实现思路,并给出完整的Ruby代码。
19.9万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 解析模式匹配规则:将模式匹配规则解析成可操作的数据结构,例如,对于哈希表模式,将键值对解析出来,对于数组模式,明确每个位置的预期类型或值。
  2. 动态生成代码:使用Ruby的元编程能力,根据解析后的模式匹配规则动态生成用于匹配的代码。这可以通过Module#define_method等方式来实现。
  3. 性能优化:在生成代码时,尽量减少不必要的计算和循环。例如,对于哈希表,优先检查键是否存在,对于数组,提前确定长度是否匹配等。

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