ruby - 动态救援条款,此代码如何工作?

标签 ruby error-handling metaprogramming

def errors_matching(&block)
  m = Module.new
  (class << m ;self; end).instance_eval do
    define_method(:===, &block)
  end
  m
end

这使我可以在Ruby中定义动态救援子句,例如:
begin
  raise 'hi'
rescue errors_matching { |e| e.class.name.include?('Runtime') } => e
  puts "Ignoring #{e.message}"
end

我不懂第一段代码。 m = Module.new的全部要点是什么,然后将self(在这种情况下为main)放入单例类中并对其执行instance_eval?

最佳答案

这个:

class << m; self end

显然与:
m.singleton_class


m.singleton_class.instance_eval { define_method(:foo) {} }

与...相同
m.define_singleton_method(:foo) {}

因此,整个errors_matching方法只是一种非常复杂的说法:
def errors_matching(&block)
  Module.new.tap do |m| m.define_singleton_method(:===, &block) end
end

关于ruby - 动态救援条款,此代码如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26506247/

相关文章:

ruby - 是否可以在 Ruby 中显式包含子模块或类?

javascript - 如何区分 jQuery .fail()

c++ - 在模板化函数中使用 unique_ptr<int[]>、vector<int> 和 int[]

c++ - 如何从元组 C++ 中过滤重复类型

在 Raku 中测试私有(private)方法

ruby - 限制 fork 进程的数量

regex - 如何仅当一组字符串中的一个匹配时才返回 true?

ruby-on-rails - 使用 S3 预签名 URL 上传一个文件,该文件将具有公共(public)读取权限

c - ENOSPC vs ENOMEM 什么时候使用?

angularjs - 在本地处理 Angular $http 错误并回退到全局错误处理