如何使Ruby函数像一个显式的’return’语句?
发布时间:2020-12-17 03:56:14 所属栏目:百科 来源:网络整理
导读:我试图用 Ruby方法做一些不寻常的事情.我想使终止行为像下面代码中的显式return语句: def terminate(data) data.upcase #I want to put a command somewhere in this scopeenddef other_method data = "cow" terminate data data = "fox"endother_method#De
我试图用
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的结果是其块中执行的最后一个语句的结果. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |