我正在尝试创建一个具有字符串修剪功能的类:
Object subclass: Trimmer [
trimleading: str [ |ch ret|
ch := (str first: 1). "get first character"
ret := str. "make a copy of sent string"
[ch = ' '] whileTrue: [ "while first char is space"
ret := (ret copyFrom: 2). "copy from 2nd char"
ch := ret first: 1. "again test first char"
].
^ret "return value is modified string"
].
trim: str [ |ret|
ret := str.
ret := (trimleading value: ret). "trim leading spaces"
ret := (trimleading value: (ret reverse)). "reverse string and repeat trim leading"
^(ret reverse) "return reverse string"
]
].
oristr := ' this is a test '
('ORI..>>',oristr,'<<') displayNl.
('FINAL>>',((Trimmer new) trim: oristr),'<<') displayNl.
但是,它没有运行并给出以下错误:
$ gst trimstring_class.st
trimstring_class.st:10: invalid class body element
trimstring_class.st:17: expected expression
问题出在哪里,如何解决?
如果我删除.
after trimleading 方法块,如下面的代码:
Object subclass: Trimmer [
trimleading: str [ |ch ret flag|
ret := str. "make a copy of sent string"
flag := true.
[flag] whileTrue: [ "while first char is space"
ch := ret first: 1. "again test first char"
ch = ' '
ifTrue: [ ret := (ret copyFrom: 2 to: ret size)] "copy from 2nd char"
ifFalse: [flag := false]
].
^ret "value is modified string"
] "<<<<<<< PERIOD/DOT REMOVED FROM HERE."
trim: str [ |ret|
ret := str.
ret := (trimleading value: ret). "trim leading spaces"
ret := (trimleading value: (ret reverse)). "reverse string and repeat trim leading"
^(ret reverse) "return reverse string"
]
].
然后代码开始运行,但因以下错误而停止:
$ gst trimstring_class.st
trimstring_class.st:15: undefined variable trimleading referenced
ORI..>> this is a test <<
Object: Trimmer new "<0x7f1c787b4750>" error: did not understand #trim:
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
Trimmer(Object)>>doesNotUnderstand: #trim: (SysExcept.st:1448)
UndefinedObject>>executeStatements (trimstring_class.st:23)
为什么trimleading
方法现在是未定义的,为什么是 gnu-smalltalk did not understand #trim:
?