MST
星途 面试题库

面试题:Ruby 函数式编程与元编程的结合应用

在Ruby中,结合函数式编程和元编程的特性,实现一个可定制的日志记录模块。该模块可以通过函数式的方式定义不同的日志记录规则,例如只记录特定类型的消息,并且利用元编程动态地为类添加日志记录方法。请详细说明实现思路和关键代码。
41.7万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 函数式编程部分:定义一些高阶函数来处理日志记录规则,例如过滤特定类型消息的函数。
  2. 元编程部分:使用Ruby的元编程能力,动态地为类添加日志记录方法。这可以通过define_method等元编程方法来实现。

关键代码

# 日志记录规则的函数式定义
def log_filter(type, messages)
  messages.select { |msg| msg[:type] == type }
end

# 元编程为类添加日志记录方法
module Logging
  def self.included(base)
    base.class_eval do
      def log_messages(messages)
        filtered_messages = log_filter(:info, messages)
        filtered_messages.each do |msg|
          puts "[INFO] #{msg[:content]}"
        end
      end
    end
  end
end

# 使用示例
class MyClass
  include Logging
end

messages = [
  { type: :info, content: 'This is an info message' },
  { type: :error, content: 'This is an error message' }
]

obj = MyClass.new
obj.log_messages(messages)

上述代码中,log_filter函数体现了函数式编程,用于过滤特定类型的日志消息。Logging模块通过include钩子方法,使用class_eval动态为包含该模块的类添加log_messages方法,展示了元编程的应用。