此代码:
((1 to: 10)
inject: (WriteStream on: String new)
into: [ :strm :each |
((each rem: 3) = 0)
ifTrue: [
strm
nextPutAll: each printString;
space;
yourself ]]) contents失败,因为strm未定义在ifTrue:块中使用的位置。为什么在那里看不见?
编辑:我在VASt和法罗尝试过。
发布于 2016-07-15 06:17:48
问题是隐含的ifFalse:分支返回nil。若要解决此问题,请尝试以下操作:
((1 to: 10)
inject: (WriteStream on: String new)
into: [ :strm :each |
((each rem: 3) = 0)
ifFalse: [strm] "This is needed to avoid nil being returned"
ifTrue: [
strm
nextPutAll: each printString;
space;
yourself ]]) contents发布于 2016-07-15 09:09:23
根据方言(可用的方法),您可以采取更短的方法。
((1 to: 10) select: [ :each | (each rem: 3) = 0 ]) joinUsing: ' '作为一条经验法则,任何collection do: [ :each | something ifTrue: [] ]都可以转化成更直接、更易读的collection select: []或collection reject: []。
这样做将把复杂性分散到几个独立的步骤(1.过滤,2.添加到流中),而不是把它全部推到一起。
或者如果你想坚持原著
(((1 to: 10) select: [ :each | (each rem: 3) = 0 ])
inject: (WriteStream on: String new)
into: [ :stream :each |
stream
nextPutAll: each printString;
space;
yourself ]) contents或
String streamContents: [ :stream |
(1 to: 10)
select: [ :each | (each rem: 3) = 0 ]
thenDo: [ :each |
stream
nextPutAll: each printString;
space
]
]不要总是这样,但当你遇到这样的情况时,要记住这一点。
https://stackoverflow.com/questions/38387689
复制相似问题