【发布时间】:2013-01-25 02:18:51
【问题描述】:
我们可以在rescue 语句之后放置一个类或模块,但在下面的代码中,我看到rescue 后面的一个方法不符合这种模式。它是如何工作的,它是如何产生它所设计的输出的?
def errors_with_message(pattern)
# Generate an anonymous "matcher module" with a custom threequals
m = Module.new
(class << m; self; end).instance_eval do
define_method(:===) do |e|
pattern === e.message
end
end
m
end
puts "About to raise"
begin
raise "Timeout while reading from socket"
rescue errors_with_message(/socket/)
puts "Ignoring socket error"
end
puts "Continuing..."
输出
About to raise
Ignoring socket error
Continuing...
【问题讨论】:
-
专业提示:如果你正确地格式化代码,它会变得更容易阅读和理解。
-
@SergioTulentsev - 是的,你之前也这么跟我说过,我一直牢记在心,就像我对教授所做的那样。在这里,我试图保持不变,但失败了。很抱歉,也请原谅我。 :(
-
别担心,继续努力:)