2013-07-17 106 views
0

(歡迎將標題更改爲更合適的標題!)操作數組:向重複元素添加出現次數

我又找到了一個Ruby/ERB問題。我有這個文件:

ec2-23-22-59-32, mongoc, i-b8b44, instnum=1, Running 
ec2-54-27-11-46, mongod, i-43f9f, instnum=2, Running 
ec2-78-62-192-20, mongod, i-02fa4, instnum=3, Running 
ec2-24-47-51-23, mongos, i-546c4, instnum=4, Running 
ec2-72-95-64-22, mongos, i-5d634, instnum=5, Running 
ec2-27-22-219-75, mongoc, i-02fa6, instnum=6, Running 

我可以處理該文件創建一個這樣的數組:

irb(main):007:0> open(inFile).each { |ln| puts ln.split(',').map(&:strip)[0..1] } 
ec2-23-22-59-32 
mongoc 
ec2-54-27-11-46 
mongod 
.... 
.... 

但我真正想要的是級聯到出現次數「mongo-鍵入」使其變成:

ec2-23-22-59-32 
mongoc1 
ec2-54-27-11-46 
mongod1 
ec2-78-62-192-20 
mongod2 
ec2-24-47-51-23 
mongos1 
ec2-72-95-64-22 
mongos2 
ec2-27-22-219-75 
mongoc2 

每個蒙戈型的數目不是固定的,它隨時間變化。任何幫助,我該怎麼做?提前致謝。乾杯!!

+0

如何定義「發生次數」?它在文件中還是計算在內?您的目的是否足以追加實例編號? –

+0

@Mark:值應該被計算。比如說,如果文件中有三個mongod條目,那麼我應該有'mongod1','mongod2','mongod3',同樣的規則也應該應用於其他Mongo實例。 MongoC,MongoD和MongoS的數量在文件中有所不同,這取決於用戶決定啓動虛擬機時的決定,並根據自己的需求自動生成文件。它回答你的問題嗎?乾杯!! – MacUsers

+0

@Mark:w.r.t.你最後一個問題,將「實例編號」附加到「mongo」不是我真正想要的,但我喜歡看到鋤頭去做它。我可能會將其用於其他目的。乾杯!! – MacUsers

回答

1

快速的答案(也許可以優化):

data = 'ec2-23-22-59-32, mongoc, i-b8b44, instnum=1, Running 
ec2-54-27-11-46, mongod, i-43f9f, instnum=2, Running 
ec2-78-62-192-20, mongod, i-02fa4, instnum=3, Running 
ec2-24-47-51-23, mongos, i-546c4, instnum=4, Running 
ec2-72-95-64-22, mongos, i-5d634, instnum=5, Running 
ec2-27-22-219-75, mongoc, i-02fa6, instnum=6, Running' 

# a hash where we will save mongo types strings as keys 
# and number of occurence as values 
mtypes = {} 
data.lines.each do |ln| 
    # get first and second element of given string to inst and mtype respectively 
    inst, mtype = ln.split(',').map(&:strip)[0..1] 
    # check if mtypes hash has a key that equ current mtype 
    # if yes -> add 1 to current number of occurence 
    # if not -> create new key and assign 1 as a value to it 
    # this is a if ? true : false -- ternary operator 
    mtypes[mtype] = mtypes.has_key?(mtype) ? mtypes[mtype] + 1 : 1 
    # combine an output string (everything in #{ } is a variables 
    # so #{mtype}#{mtypes[mtype]} means take current value of mtype and 
    # place after it current number of occurence stored into mtypes hash 
    p "#{inst} : #{mtype}#{mtypes[mtype]}" 
end 

輸出:

# "ec2-23-22-59-32 : mongoc1" 
# "ec2-54-27-11-46 : mongod1" 
# "ec2-78-62-192-20 : mongod2" 
# "ec2-24-47-51-23 : mongos1" 
# "ec2-72-95-64-22 : mongos2" 
# "ec2-27-22-219-75 : mongoc2" 

相當strightforward我想。如果你不明白的東西 - 讓我知道。

+0

非常感謝,它工作得很好。我想我大部分都能理解,但你能解釋價值計算的第四行嗎?乾杯!! – MacUsers

+0

添加了一些評論 –