1
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(在這種情況下是主要的)放在單例類中並在其上執行instance_eval是什麼?
澄清的一句話:OP與我聯繫,並私下向我指出這個帖子。原始代碼來自我寫的Exceptional Ruby。這本書的寫作大多與1.8.7兼容,其中'define_singleton_method'不存在。 「tap」在1.8.7中是全新的,而不是衆所周知的。 – Avdi 2014-11-25 15:59:54