【发布时间】:2012-01-28 16:26:42
【问题描述】:
在 Ruby 中,我想在另一个对象中捕获在一个对象上生成的 NoMethodError,然后将一些值返回到引发异常的位置并继续执行。有没有现成的方法可以做到这一点?
我想出的最好的是:
class Exception
attr_accessor :continuation
end
class Outer
def hello
puts "hello"
end
class Inner
def world
puts "world"
end
def method_missing(method, *args, &block)
x = callcc do |cc|
e = RuntimeError.exception(method)
e.continuation = cc
raise e
end
return x
end
end
def inner(&block)
inner = Inner.new
begin
inner.instance_eval(&block)
rescue => e
cc = e.continuation
cc.call(hello())
end
inner
end
end
o = Outer.new
o.inner do
hello
world
end
打印出来
hello
world
使用 Ruby 现有的元编程库有没有更好的方法来做到这一点?基本上,我不确定 callcc 是否会继续存在。
谢谢。
【问题讨论】:
标签: ruby metaprogramming