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/