为什么此方法的返回部分不起作用 [英] Why this method's return part is not working

查看:88
本文介绍了为什么此方法的返回部分不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个返回新值的方法.以下代码是从此处修改的:

I am trying to write a method which returns a new value. Following code is modified from here:

| stripChars |
stripChars := [ :string :chars |    
    str := string reject: [ :c | chars includes: c ].
    str displayNl.          "THIS WORKS."
    ^ str                   "THIS DOES NOT WORK."
].

newstr := stripChars 
    value: 'She was a soul stripper. She took my heart!'
    value: 'aei'.
newstr displayNl.

尽管上面的函数创建并显示了新字符串,但返回或接收返回的新字符串时出错:

Although above function creates new string and displays it, there is error in returning or receiving returned new string:

$ gst make_fn_ques.st
Sh ws  soul strppr. Sh took my hrt!
Object: 'Sh ws  soul strppr. Sh took my hrt!' error: return from a dead method context
SystemExceptions.BadReturn(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.BadReturn class(Exception class)>>signal (ExcHandling.st:151)
String(Object)>>badReturnError (Object.st:1389)
UndefinedObject>>executeStatements (make_fn_ques.st:10)
nil

问题出在哪里,如何解决?感谢您的帮助.

Where is the problem and how can this be solved? Thanks for your help.

推荐答案

The

^ str

不是从块返回(stripChars),而是从封闭方法返回(非本地返回).

does not return from the block (stripChars), but from the enclosing method instead (non-local return).

显然,GNU Smalltalk不允许您以这种方式从传递给gst的脚本中返回.

Apparently GNU Smalltalk does not allow you to return from the script that you pass to gst in this way.

只需删除^,并仅保留str作为该块的最后一个表达式.这将导致str是该块的返回值.

Just drop the ^, and keep only str as the last expression of the block. That will cause str to be the return value of the block.

这篇关于为什么此方法的返回部分不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆