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-type”的出现次数,使其变为:

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

每个 mongo-type 的数量不是固定的,它会随着时间而变化。任何帮助我该怎么做?提前致谢。干杯!!

4

1 回答 1

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"

我认为相当直截了当。如果您有什么不明白的地方,请告诉我。

于 2013-07-17T13:11:32.613 回答