我试图用
Ruby方法做一些不寻常的事情.我想使终止行为像下面代码中的显式return语句:
def terminate(data) data.upcase #I want to put a command somewhere in this scope end def other_method data = "cow" terminate data data = "fox" end other_method #Desired response #> "COW" #Actual response in everything that we try #> "fox"
我希望other_method返回“COW”.具体来说,通过使’terminate’作为显式返回语句起作用.有什么我可以投掷/加注会做到这一点?或者其他一些hacky方式我可以强迫这种行为?
目前,在我们的代码中,我们始终使用(在大型代码库中经常更改它的许多很多实例):
return foo! param1,param2 return foo2! param1,param2 return foo3! param1,param2
我们想用以下内容替换:
foo! param1,param2 foo1! param1,param2 foo2! param1,param2
foo没有别的办法!在我们的代码库中按设计使用.它基本上是语法糖.
解决方法
throw / catch会这样做.
在调用Kernel#catch时包装方法的内容:
def something catch :return do foo! 123,456 end end
有#foo!拨打Kernel#throw:
def foo!(*args) throw :return,args end
调用#throw时,会导致异常被#catch语句捕获.然后#catch语句的结果是赋予#throw语句的值.因此:
p something # [123,456]
如果未调用#throw,则#catch的结果是其块中执行的最后一个语句的结果.