如何连接do块中的字符串?

时间:2016-02-25 19:16:54

标签: smalltalk gnu-smalltalk

我试图通过数组并将该数组中的字符添加到另一个对象。问题是我一直收到错误"字符实例不可索引"。但是,当我运行tag:= tag,在do块之外的char时,它就会起作用。

meetingsArray = ["boardInvestorsMeeting", "clientMeeting", "clientMeeting", "clientMeeting", "waterCoolerChat", "waterCoolerChat",  "waterCoolerChat", "waterCoolerChat"]
counts = Hash.new(0)
meetingsArray.each { |name| counts[name] += 1 }

counts.each do |k,v|
    case v
    when 1
        puts "Week of the 1st: #{k}" 
    when 2
        puts "Week of the 1st: #{k}"
        puts "Week of the 8th: #{k}"
    when 3
        puts "Week of the 1st: #{k}"
        puts "Week of the 8th: #{k}"
        puts "Week of the 15th: #{k}"
    when 4
        puts "Week of the 1st: #{k}"
        puts "Week of the 8th: #{k}"
        puts "Week of the 15th: #{k}"
        puts "Week of the 22nd: #{k}"
    end
end

1 个答案:

答案 0 :(得分:3)

,定义为

Collection>>, aCollection
^self copy addAll: aCollection; yourself

因此尝试对您的单个字符进行操作,就像它是一个集合一样。这解释了错误。

对于较大的集合,您不希望使用,进行构建,因为每次都会发生复制。因此,请使用流媒体协议:

|data tag|
data := '123456778'.
tag := String streamContents: [:s |
    data do: [ :char |
    s nextPut: char]]

另请查看Collection>>do:separatedBy:以在数据之间添加分隔符。

[编辑]啊,好吧,那就像

|data tag tags state|
data := '<html>bla 12 <h1/></html>'.
state := #outside.
tags := OrderedCollection new.
tag := ''.
data do: [ :char |
    state = #outside ifTrue: [
        char = $< ifTrue: [ 
            state := #inside.
            tag := '' ]]
    ifFalse:  [ 
         char = $> ifTrue: [ 
            state := #outside.
            tags add: tag] 
        ifFalse: [ tag := tag, (char asString)]]].
tags

"an OrderedCollection('html' 'h1/' '/html')"