Why this method's return part is not working

会有一股神秘感。 提交于 2019-12-11 15:29:19

问题


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.


回答1:


The

^ str

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

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

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.



来源:https://stackoverflow.com/questions/56100101/why-this-methods-return-part-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!