2014-10-22 51 views
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是什麼?

回答

1

此:

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 
+0

澄清的一句話:OP與我聯繫,並私下向我指出這個帖子。原始代碼來自我寫的Exceptional Ruby。這本書的寫作大多與1.8.7兼容,其中'define_singleton_method'不存在。 「tap」在1.8.7中是全新的,而不是衆所周知的。 – Avdi 2014-11-25 15:59:54